0

Array One:

 array1 = [{
        "id": 1,
        "name": "aaaaa",
        "attr": [{"attr_code": "a_id", "value": "5"}]
      },
      {
        "id": 2,
        "name": "bbbbb",
        "attr": [{"attr": "a_id", "value": "4"}]
      }]

Array Two:

array2 = [{
    "id": 4,
    "name": "bef",
  },
  {
    "id": 5,
    "name": "bcd",
  }]

Resulting Array:

 resultingArray =  [{
    "id": 1,
    "name": "aaaaa",
    "attr": [{"attr_code": "a_id", "value": "5"}],
    "a_id" :   {"id": 5, "name": "bcd"}
  },
    {
      "id": 2,
      "name": "bbbbb",
      "attr": [{"attr": "a_id", "value": "4"}],
      "a_id" : {"id": 4, "name": "bef"}
    }]

I am looking to add the array2 objects into array1 based on id's of array2. I have tried using map function on both the arrays to compare and add the object but I didn't succeed. Can you please suggest me how to do it?

Thank you

1

5 Answers 5

1

Add the array2 objects into array1 based on ids of array2.

let array1 = 
[
  {
    "id": 1,
    "name": "aaaaa",
    "attr": [{"attr_code": "a_id", "value": "5"}]
  },
  {
    "id": 2,
    "name": "bbbbb",
    "attr": [{"attr": "a_id", "value": "4"}]
  }
];
      
let array2 = [{
    "id": 4,
    "name": "bef",
  },
  {
    "id": 5,
    "name": "bcd",
  }
];
 
let resultingArray=[]; 

array1.forEach(function(element) {
  element['a_id'] = [];
  element['attr'].forEach(function(attr) {
        element['a_id'].push(array2.find(function(item) {
        return item.id == attr.value;
      }));
   });
  resultingArray.push(element)
});

console.log(resultingArray);

Sign up to request clarification or add additional context in comments.

Comments

0

I presume you intend to extract the object whose ID is equal to the value field the in the each object in array1.

var array1 = [{
        "id": 1,
        "name": "aaaaa",
        "attr": [{"attr_code": "a_id", "value": "5"}]
      },
      {
        "id": 2,
        "name": "bbbbb",
        "attr": [{"attr": "a_id", "value": "4"}]
      }];

var array2 = [{
    "id": 4,
    "name": "bef",
  },
  {
    "id": 5,
    "name": "bcd",
  }];

var resultingArray = [];
for(var i = 0; i < array1.length; i++) {
    resultingArray[i] = array1[i];
    for(var j = 0; j < array2.length; j++) {
        if(resultingArray[i].attr[0].attr_code.value === array2[j].id) {
            resultingArray[i].push("a_id": array2[j]);
        }
    }
} 

You just need to lop through array1, and for each object in array1, you need to find corresponding objects in array2 which match the criterion.

Comments

0

You can use array map and array index to do:

var array1 = [{
        "id": 1,
        "name": "aaaaa",
        "attr": [{"attr_code": "a_id", "value": "5"}]
      },
      {
        "id": 2,
        "name": "bbbbb",
        "attr": [{"attr": "a_id", "value": "4"}]
      }];
var array2 = [{
    "id": 4,
    "name": "bef",
  },
  {
    "id": 5,
    "name": "bcd",
  }];
var result = array1.map(current=>{
  //find index of attr in array2
  let index = array2.findIndex(c=>{
    if (c['id']===(Number(current['attr'][0]['value'])))
      return c;
  });
  current["a_id"] = array2[index];
  return current;
});
console.log(result);

Comments

0

Please check if the following code suites your requirement. You may need to make some changes.

function mergeArrays3 (arr1, arr2) {
 return arr1.map((value, index) => {
  let object = null;
  let result = {...value};
  for (let element of arr2) {
   if (element.id == parseInt(value.attr[0].value)) {
    object = element;
    break;
   }
  }
  if (object != null) {
   let attr = value.attr[0];
   if (attr.hasOwnProperty("attr")) {
    result[value.attr[0].attr] = object;
   } else if (attr.hasOwnProperty("attr_code")) {
    result[value.attr[0].attr_code] = object;
   }
  }
  return result;
 });
}

I loop over first array and find an element in second array matching id of value.attr[0].value. If found then i added this object in the first array at key of value.attr[0].attr or value.attr[0].attr_code.

Comments

0

I have tried using map function on both the arrays to compare and add the object but I didn't succeed

Below is the functional programming approach using map():

/* GIVEN */
const array1 = [{
    "id": 1,
    "name": "aaaaa",
    "attr": [{
      "attr_code": "a_id",
      "value": "5"
    }]
  },
  {
    "id": 2,
    "name": "bbbbb",
    "attr": [{
      "attr": "a_id",
      "value": "4"
    }]
  }
]

const array2 = [{
    "id": 4,
    "name": "bef",
  },
  {
    "id": 5,
    "name": "bcd",
  }]

/* From array2, make an object keyed by the 'id' field. We'll use this as a key-value lookup table  */
const lookupTable = array2.reduce((accum, item) => {
    accum[item.id.toString()] = item
    return accum
  }, {})
  
  
console.log('***LOOKUP TABLE***\n', lookupTable) // result is an object we use to lookup

/* From array1, we append data from the lookup table */
const final = array1.map(item => {
    item.a_id = lookupTable[item.attr[0].value]
    return item
  })

console.log("***RESULT***\n", final)

Hope this helps. Cheers,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.