Skip to content Skip to sidebar Skip to footer

Pull Items From One Array And Add To An Existing Array Javascript

I have existing array and would like to add another object array to each item where the IDs match. var existingData = [ { 'id': '0100', 'name': 'name 1',

Solution 1:

It's far more efficient to create a hash map from data2 so you only ever iterate that array once. The keys would be the id's

Then while you iterate existingData it is a simple merge

var candidatesById = data2.reduce(function(a, c){
   c.relatedId.forEach(function(id){
       a[id] = a[id] || [];
       a[id].push(c.CandidateName);           
   });
   return a;
},{});

existingData.forEach(function(item){
    item.CandidateName = candidatesById[item.id] || [];// empty array if no match
})

Solution 2:

Try this! The concept being, use the initial data, loop through and search for IDs, add applicable data.

Do note that this isn't a particularly efficient solution.

var existingData = [{
  "id": "0100",
  "name": "name 1",
  "message": [
    "Lorem blah blah 1",
    "Lorem blah blah 1.1"
  ]
}, {
  "id": "0200",
  "name": "name 2",
  "message": [
    "Lorem blah blah 2",
    "Lorem blah blah 2.1",
    "Lorem blah blah 2.2"
  ]
}, {
  "id": "0300",
  "name": "name 3",
  "message": [
    "Lorem blah blah 3",
    "Lorem blah blah 3.1",
    "Lorem blah blah 3.2",
    "Lorem blah blah 3.3",
    "Lorem blah blah 3.4"
  ]
}];

var toCombine = [{
  "CandidateName": "Mary",
  "relatedId": ["0100", "0200"]
}, {
  "CandidateName": "John",
  "relatedId": ["0200"]
}, {
  "CandidateName": "Peter",
  "relatedId": ["0300", "0100"]
}, {
  "CandidateName": "Paul",
  "relatedId": ["0300"]
}];

functionmerge() {
  existingData.forEach(function(initialItem) {
    toCombine.forEach(function(referenceItem) {
      if (referenceItem.relatedId.indexOf(initialItem.id) >= 0) {
        if (!Array.isArray(initialItem.CandidateName)) {
          initialItem.CandidateName = [];
        }
        initialItem.CandidateName.push(referenceItem.CandidateName);
      }
    });
  });
  console.log(existingData);
}

merge();

Solution 3:

Here is another ES6 solution:

data2.forEach( function (obj) {
    obj.relatedId.forEach( id =>this.get(id).candidateName.push(obj.CandidateName));
}, newMap(existingData.map (
    obj => [obj.id, Object.assign(obj, { 'candidateName': [] } )] 
)));

var existingData = [
    {
        "id": "0100",
        "name": "name 1",
        "message": [
            "Lorem blah blah 1",
            "Lorem blah blah 1.1"
        ]
    },
    {
        "id": "0200",
        "name": "name 2",
        "message": [
            "Lorem blah blah 2",
            "Lorem blah blah 2.1",
            "Lorem blah blah 2.2"
        ]
    },
    {
        "id": "0300",
        "name": "name 3",
        "message": [
            "Lorem blah blah 3",
            "Lorem blah blah 3.1",
            "Lorem blah blah 3.2",
            "Lorem blah blah 3.3",
            "Lorem blah blah 3.4"
        ]
    }
];

var data2 = [
  {"CandidateName": "Mary", "relatedId": ["0100", "0200"]},
  { "CandidateName": "John", "relatedId": ["0200"]},
  { "CandidateName":"Peter", "relatedId": ["0300", "0100"]},
  { "CandidateName": "Paul", "relatedId": ["0300"]}
];

data2.forEach( function (obj) {
    obj.relatedId.forEach( id =>this.get(id).candidateName.push(obj.CandidateName));
}, newMap(existingData.map (
    obj => [obj.id, Object.assign(obj, { 'candidateName': [] } )] 
)));

console.log(existingData);

This turns the existingData into a map, keyed by id, while adding the candidateName array (empty) to the objects.

This map is passed as the second argument to forEach, thus defining it as the this object.

Inside the forEach on data2 elements, the relatedId values are iterated and for each of these id values the corresponding existingData object's candidateName array is extended with the CandidateName.

Solution 4:

May be we can do something like this in ES6 too; Well.. i create a hash table from data2 and use it as a this object in map.

var existingData = [
    {
        "id": "0100",
        "name": "name 1",
        "message": [
            "Lorem blah blah 1",
            "Lorem blah blah 1.1"
        ]
    },
    {
        "id": "0200",
        "name": "name 2",
        "message": [
            "Lorem blah blah 2",
            "Lorem blah blah 2.1",
            "Lorem blah blah 2.2"
        ]
    },
    {
        "id": "0300",
        "name": "name 3",
        "message": [
            "Lorem blah blah 3",
            "Lorem blah blah 3.1",
            "Lorem blah blah 3.2",
            "Lorem blah blah 3.3",
            "Lorem blah blah 3.4"
        ]
    }
],
 data2 = [
  {"CandidateName": "Mary", "relatedId": ["0100", "0200"]},
  { "CandidateName": "John", "relatedId": ["0200"]},
  { "CandidateName":"Peter", "relatedId": ["0300", "0100"]},
  { "CandidateName": "Paul", "relatedId": ["0300"]}
],

newExistingData = existingData.map(function(o){
                                     o.CandidateName = this[o.id];
                                     return o;
                                   }, data2.reduce((h,o) => (o.relatedId.reduce((p,c) => (p[c] ? p[c].push(o.CandidateName)
	                                                                                       : p[c] = [o.CandidateName],p),h),h),{}));
console.log(newExistingData);

Post a Comment for "Pull Items From One Array And Add To An Existing Array Javascript"