Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

javascript - How to get all properties of the second array of objects when comparing with the first?

I am using JavaScript with lodash and have two array of objects as follows:

objArr1 = [{'x': 1, 'y': 2, 'z': 3}, {'x': 10, 'y': 20, 'z': 30}, {'x': 100, 'y': 200, 'z': 300}, {'x': 1000, 'y': 2000, 'z': 3000}, {'x': 10000, 'y': 20000, 'z': 30000}]

objArr2 = [{'x': 1, 'y': 2, 'a': 5}, {'x': 10, 'y': 20, 'a': 6}, {'x': 100, 'y': 200, 'a': 9}]

I am using the matching key as 'x' and I am able to get:

_.intersectionBy(objArr1, objArr2, 'x')

[{'x': 1, 'y': 2, 'z': 3}, {'x': 10, 'y': 20, 'z': 30}, {'x': 100, 'y': 200, 'z': 300}]

However, I also need to get the 'a' property in the second array of objects.

e.g.

[{'x': 1, 'y': 2, 'z': 3, 'a': 5}, {'x': 10, 'y': 20, 'z': 30, 'a': 6}, {'x': 100, 'y': 200, 'z': 300, 'a': 9}]

Couldn't seem to figure out using lodash.

Please help! Thanks!

question from:https://stackoverflow.com/questions/65894808/how-to-get-all-properties-of-the-second-array-of-objects-when-comparing-with-the

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This would be relatively simple to roll yourself without lowdash. The following combineArrays function takes a key and any number of arrays. It iterates over those arrays and puts any values into an object indexed by the desired key. Finally, Object.values grabs the final desired array.

const objArr1 = [{'x': 1, 'y': 2, 'z': 3}, {'x': 10, 'y': 20, 'z': 30}, {'x': 100, 'y': 200, 'z': 300}, {'x': 1000, 'y': 2000, 'z': 3000}, {'x': 10000, 'y': 20000, 'z': 30000}];

const objArr2 = [{'x': 1, 'y': 2, 'a': 5}, {'x': 10, 'y': 20, 'a': 6}, {'x': 100, 'y': 200, 'a': 9}];

function combineArrays(key, ...arrs) {
  const result = {};
  const counts = {};
  arrs.forEach(arr => {
    arr.forEach(el => {
      result[el[key]] = { ...result[el[key]], ...el }; 
      counts[el[key]] = (counts[el[key]] || 0) + 1;
    });
  });
  return Object.values(result).filter(obj => 
    counts[obj[key]] > 1
  );
}

console.log(
  combineArrays("x", objArr1, objArr2)
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...