简体   繁体   中英

Add values from one array to object with specified key & index

Im using the following code,

jQuery.each(aDataSel, function(index, oData) {
        oPushedObject = {};
        aSelectedDataSet.push(fnCreateEnt(aProp, oData, oPushedObject));
    });

This is aSelectedDataSet values

在此处输入图片说明

and this is the values of OData

在此处输入图片说明

What I need is that before I do the push is to fill the listTypeGroup & listTypeGroupDescription (with the red arrow ) with values that Are inside the oData -> ListTypeGroupAssigment -> result (listTypeGroup & listTypeGroupDescription) , The index is relevant since I want to add just the value of the index in each iteration (since this code is called inside outer loop and the index determine the current step of the loop) ,How it can be done nicely?

The result contain 100 entries (always) and the a selected data will have 100 entries at the end...

Update :)

Just to be clear In the pic I show the values which is hardcoded for this run but the values can be any values, we just need to find the match between the both objects values...

I mean to find a match between to_ListTypeGroupAssigment in both object (which in this case exist ) and if in oData there is result bigger then one entry start with the matching ...

UPDATE2 - when I try Dave code the following happen for each entry, This happen in the Jquery.extend line...any idea how to overcome this?

在此处输入图片说明

The following hard-coded of Dave :-) work perfect but I need generic code which doesnt refer to specific field name

        jQuery.each(aDataSet, function(index, oData) {
            oPushedObject = {};
            fnCreatePushedEntry(aProperties, oData, oPushedObject);
            var result = oData.to_ListTypeGroupAssignment.results[index];
            oPushedObject.to_ListTypeGroupAssignment = {
                ListTypeGroup: result.ListTypeGroup,
                ListTypeGroupDescription: result.ListTypeGroupDescription
            };

            aSelectedDataSet.push(oPushedObject);
        });

Im stuck :(any idea how to proceed here ?what can be wrong with the extend ? should I use something else ? Im new to jQuery...:)

I think that this happen(in Dave answer) because the oData[key] is contain the results and not the specified key (the keyValue = to_ListTypeGroupAssignment ) which is correct but we need the value inside the object result per index...

在此处输入图片说明

var needValuesForMatch = {
    ListTypeGroup: 'undefined',
    ListTypeGroupDescription: 'undefined',
  }
  //Just to show that oPushedObject can contain additional values just for simulation 
var temp = {
  test: 1
};

//------------------This object to_ListTypeGroupAssigment should be filled (in generic way :) ------
var oPushedObject = {
  temp: temp,
  to_ListTypeGroupAssignment: needValuesForMatch
};

oPushedObject is one instance in aSelectedDataSet

and after the matching I need to do the follwing:

aSelectedDataSet.push(oPushedObject);

If I am understanding you correctly this should just be a small change:

jQuery.each(aDataSel, function(index, oData) {
  oPushedObject = {};
  fnCreateEnt(aProp, oData, oPushObj);

  //get all the properties of oData and clone into matching properties of oPushObj
  Object.getOwnPropertyNames(oData).forEach(function(key) {
    if (oPushObj.hasOwnProperty(key)) {
      //oPushObj has a matching property, start creating destination object
      oPushObj[key] = {};
      var source = oData[key];
      var destination = oPushObj[key];

      //can safely assume we are copying an object. iterate through source properties
      Object.getOwnPropertyNames(source).forEach(function(sourceKey) {
        var sourceItem = source[sourceKey];

        //handle property differently for arrays
        if (Array.isArray(sourceItem)) {
          //just copy the array item from the appropriate index
          destination[sourceKey] = sourceItem.slice(index, index + 1);
        } else {
          //use jQuery to make a full clone of sourceItem
          destination[sourceKey] = $.extend(true, {}, sourceItem);
        }

      });
    }
  });

  aSelectedDataSet.push(oPushedObject);
});

It is unclear what exactly your fnCreateEnt() function returns though. I am assuming it is the populated oPushObj but it's not entirely clear from your question.

Is this what you're after:

OPTION ONE - DEEP CLONE FROM oData TO aSelectedDataSet

aSelectedDataSet.forEach(function(currentObject,index){

     for (var childObject in currentObject) {
         if (! currentObject.hasOwnProperty(childObject))
             continue;

          var objectToClone = oData[childObject]['results'][index];

          if(objectToClone)
              $.extend(true,currentObject[childObject],objectToClone);
     }
  });

Here is your data in a fiddle with the function applied: https://jsfiddle.net/hyz0s5fe/

OPTION TWO - DEEP CLONE FROM oData ONLY WHERE PROPERTY EXISTS IN aSelectedDataSet

    aSelectedDataSet.forEach(function(currentObject,index){

     for (var childObject in currentObject) {
          if (! currentObject.hasOwnProperty(childObject))
            continue;

          if(typeof currentObject[childObject] !== 'object')
            continue;

          for(var grandChildObject in currentObject[childObject]) {

               var objectToClone = oData[childObject]['results'][index][grandChildObject];

                if(typeof objectToClone === 'object') {
                        $.extend(true,currentObject[childObject][grandChildObject],objectToClone);
                } else {
                        currentObject[childObject][grandChildObject] = objectToClone;
                }
          }
     }

Fiddle for option 2: https://jsfiddle.net/4rh6tt25/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM