Merge corresponding objects inside array JS

Related searches

How can I merge two arrays of objects where one object from one array is corresponding with one object in another array. Object which are not corresponding should be preserved. id and uid is corresponding condition.

const data1 = [{
  id: 1,
  someKey1: 'someValue2'
}, {
  id: 2,
  someKey2: 'someValue2'
}, {
  id: 3,
  someKey3: 'someValue3'
}]
const data2 = [{
  uid: 1,
  someKey4: 'someValue4'
}, {
  uid: 2,
  someKey5: 'someValue5'
}]

// expected result:

[{
  someKey1: 'someValue2',
  someKey4: 'someValue4'
}, {
  someKey2: 'someValue2',
  someKey5: 'someValue5',
  {
    id: 3,
    someKey3: 'someValue3'
  }
}]

You can grab all ids and uids from both sets of arrays and put them into a set, and then turn that set back into an array to get a list of unique ids/uids. Then, you can create maps for both arrays. Mapping the ids/uids to hold their corresponding object properties. Using the unique array of ids/uids, you can then .map() each id to its corresponding object held in the Maps like so:

const data1 = [{ id: 1, someKey1: 'someValue2'}, { id: 2, someKey2: 'someValue2' }, { id: 3, someKey3: 'someValue3' }]
const data2 = [{ uid: 1, someKey4: 'someValue4'}, { uid: 2, someKey5: 'someValue5' }];
const getMap = (arr, id) => new Map(arr.map(({[id]:_id, ...r}) => [_id, {...r}]));

const ids = [...new Set(data1.map(({id}) => id).concat(data2.map(({uid}) => uid)))];

const data1Map = getMap(data1, 'id');
const data2Map = getMap(data2, 'uid');

const result = ids.map(id => ({...(data1Map.get(id) || {}), ...(data2Map.get(id) || {})}));
console.log(result);

Combining JavaScript Arrays, Analyzing various techniques for combining/merging JavaScript Arrays. So, if the array being added on has a million items in it, you'd almost� #2 Ways to Merge Arrays in JavaScript Here are 2 ways to combine your arrays and return a NEW array. I like using the Spread operator. But if you need older browser support, you should use Concat.

You can create a function that iterates the array of data and put its object in a new array where the index is the id or uid

const data1 = [{ id: 1, someKey1: 'someValue2'}, { id: 2, someKey2: 'someValue2' }, { id: 3, someKey3: 'someValue3' }]
const data2 = [{ uid: 1, someKey4: 'someValue4'}, { uid: 2, someKey5: 'someValue5' }]

let result = [];
result = mergeIntoResult(result, data1, "id");
result = mergeIntoResult(result, data2, "uid");

console.log(JSON.stringify(result));

function mergeIntoResult(resultArray, dataArray, idProperty) {
    return dataArray.reduce((acc,curr) => {
      const index = curr[idProperty];
      acc[index] = acc[index] || {}; //Take existing object or create default
      acc[index] = {...acc[index], ...curr}; //Insert object data
      delete acc[index][idProperty]; //Delete the "id" or "uid" field from the new object
      return acc;
    }, resultArray);
}

How to Merge Objects in JavaScript, To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ) Use the Object.assign() method� Definition and Usage The concat () method is used to join two or more arrays. This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

Here's another approach, which is not performance optimized and is less concise than the other answers, but breaks the steps down to make clear what's happening.

const data1 = [{ id: 1, someKey1: 'someValue2'}, { id: 2, someKey2: 'someValue2' }, { id: 3, someKey3: 'someValue3' }]
const data2 = [{ uid: 1, someKey4: 'someValue4'}, { uid: 2, someKey5: 'someValue5' }]

function mergeProperties(set1, linkingProperty1, set2, linkingProperty2){

  const keys1 = set1.map( item => item[linkingProperty1] );
  const keys2 = set2.map( item => item[linkingProperty2] );
  const mergedKeys = keys1.concat(keys2);
  const filteredKeys = mergedKeys.filter( key => !!key || key === 0); //truthy or actually number 0
  const uniqueKeys = filteredKeys.filter((a, b) => filteredKeys.indexOf(a) === b);

  // now we have a complete list, with no duplicates, of all possible ids

  const mergedArray = uniqueKeys.reduce( (accumulator, key) => {
      const resultInSet1 = set1.find( item => item[linkingProperty1] === key );
      const resultInSet2 = set2.find( item => item[linkingProperty2] === key );
      let item = {};
      if(resultInSet1){
        delete resultInSet1[linkingProperty1];
        item = {...resultInSet1};
      }
      if(resultInSet2){
        delete resultInSet2[linkingProperty2];
        item = {...item, ...resultInSet2};
      }
      return [...accumulator, item];
  }, []);

  return mergedArray;
}

console.log( mergeProperties(data1,"id",data2,"uid") );

How can I merge an array of Objects with same keys in ES6 , JavaScript merge array of objects by key (es6), function mergeArrayObjects(arr1 @param {string[]} keys - List of keys corresponding to their accociated values. Javascript objects are key-value paired dictionaries. We can merge different objects into one using the spread (…) operator. object1 = {object2, object3, } Example 2: Suppose the objects have the same keys. In this case, the value of the key of the object which appears later in the distribution is used.

You can use map function. In addition, you can use Map collection to access items with O(1):

const createObj = (fooObj, keyToFilter) => {
  if (fooObj)
    return Object.fromEntries(Object.entries(fooObj).filter(([k, v])=> k != keyToFilter ));
  return null;
}    

const result = data1.map(s=> ({...createObj(s,'id'), ...createObj(maps.get(s.id),'uid')}));

An example:

const data1 = [{
  id: 1,
  someKey1: 'someValue2'
}, {
  id: 2,
  someKey2: 'someValue2'
}, {
  id: 3,
  someKey3: 'someValue3'
}];

const data2 = [{
  uid: 1,
  someKey4: 'someValue4'
}, {
  uid: 2,
  someKey5: 'someValue5'
}]

let maps = new Map(data2.map(s=> [s.uid, s]));
const createObj = (fooObj, keyToFilter) => {
  if (fooObj)
    return Object.fromEntries(Object.entries(fooObj).filter(([k, v])=> k != keyToFilter ));
  return null;
}

const result = data1.map(s=> ({...createObj(s,'id'), ...createObj(maps.get(s.id),'uid')}));
console.log(result);

Merge objects with corresponding key values from two different , Union of objects in javaScript based on unique value, Merging of two or more objects; Merging of object into an Array; Merging What if both the object has same� On average I work with JSON data 18 times a week. And I still need to google for specific ways to manipulate them almost every time. What if there was an ultimate guide that could always give you the answer? In this article, I'll show you the basics of working with object arrays in JavaScript. If you ever worked with a JSON structure, you've worked with JavaScript objects. Quite literally

Here is a function that will do what you're looking for:

const objectMerge = (sourceData, joinData) => 
  sourceData.map(item => {
    const { id, ...restOfItem } = item
    const foundJoins = joinData.filter(obj => obj.uid === id)
    if (foundJoins.length === 0) {
      return item
    }
    const dataFromJoins = foundJoins.reduce((result, join) => { 
      // Return everything in the object except the UID
      const { uid, ...restOfFields } = join
      return Object.assign({}, result, restOfFields)
    }, {})
    return Object.assign({}, restOfItem, dataFromJoins)
  })

You can see it working here: https://repl.it/@RobBrander/Object-Merger

array_merge - Manual, Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in We merge each child with its respective parent Arrays are Objects. Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John:

So far, all the arrays we’ve dealt with have been “flat” arrays; each array element contains a single value, such as a number, string, or object. However, like most programming languages, JavaScript lets you create arrays inside arrays, known as nested arrays. In a nested array, the elements of one array are themselves arrays. For example:

A popular serialization format is called JSON (pronounced “Jason”), which stands for JavaScript Object Notation. It is widely used as a data storage and communication format on the Web, even in languages other than JavaScript. JSON looks similar to JavaScript’s way of writing arrays and objects, with a few restrictions.

Comments
  • Your expected result is not valid Javascript syntax.
  • To expand on @connexo comment, the object starting {id: 3 in the expected result needs a key in the outer object.
  • What if an item is in the second set of data, but not the first?
  • What if an item si in data 2 but not in data 1?
  • Will be ignored. Does that need to be preserved?
  • That's what the OP said. "Object which are not corresponding should be preserved."