Home > Enterprise >  add another object to another and loop data into it
add another object to another and loop data into it

Time:06-24

How can I map through the compositions array (in the sample object), and populate the compositions array of the objToAdd object with the data.

const sample = {
  links: {
"compositions": [
  {
    "modelId": 103889,
    "id": 164703
  },
  {
    "modelId": 103888,
    "id": 164704
  }
]
 }
}

const objToAdd = {
compositions: []
};

CodePudding user response:

So you want to fill the compositions array of the objToAdd object with the data in the compositions array of the links<sample object:

const compositionsObject = (sample['links'])['compositions'];
objToAdd['compositions'].push(compositionsObject);

Firstly to get the compositions data from sample you should 'catch' the links object : sample['links']. Then you need to get the data inside the compositions object that's why we wrap the (sample['links']) and get the data from the object that has the key 'compositions'

The compositionsObject has the following data:

[{"modelId":103889,"id":164703},{"modelId":103888,"id":164704}] 

Short summary: object[key1] => Gets the value of the key1

(object[key1])[key2] => Gets the value of the key2 inside the object that has as a key the 'key1' key.

CodePudding user response:

If you don't have static data but you have dynamic data you can do the following solution:

const sample = {
  links: {
"compositions": [
  {
    "modelId": 103889,
    "id": 164703
  },
  {
    "modelId": 103888,
    "id": 164704
  }
]
 }
}

const objToAdd = {
   compositions: []
};

const keyToMap = 'compositions';
const keyToAdd = 'compositions';

function findArray(object){
    if(object.hasOwnProperty(keyToMap))
        return object;

    for(var i=0; i<Object.keys(object).length; i  ){
        if(typeof object[Object.keys(object)[i]] == "object"){
            var o = findArray(object[Object.keys(object)[i]]);
            if(o != null)
                return o;
        }
    }
    return null;
}

const compositionsObject = findArray(sample);

objToAdd[keyToAdd].push(compositionsObject[Object.keys(compositionsObject)[0]]);

console.log('Result', objToAdd)

You can keep the name of the key you want to map in the 'keyToMapp' const and the key you want to add this data to as 'keyToAdd'.

Add a recursive function findArray that has one parameter the object you map, in this case the sample object. The first condition is the 'final' result, we ask if the sample object has the keyToMap which in this case is 'compositions'. If it finds the object with this key, it returns that object. If it doesn't find the object with that key, it iterates through object keys until it finds an object (typeof object) and retries (re-enters the function = recursive) with the new object found.

In the compositionsObject we keep the object we find with the key = keyToMap. After that we push it's values to the object with key = keyToAdd

  • Related