将两个具有相同属性的对象组合成数组值Javascript

问题描述 投票:0回答:1

我有两个对象,其中第二个对象键是第一个对象的属性(projectID);

**OBJ1** 
[0: { projectID: 1234, prop1: "apple", prop2: "banana", prop3: "choc"},
 1: { projectID: 8765, prop1: "apple", prop2: "banana", prop3: "choc"}] 
**OBJ2**
[1234: {prop1: "gen", prop2: "home", prop3: "home"}, 
8765:{prop1 :"gone", prop2:"done", prop3: "say"}]

我有一个过滤功能

Object.keys(OBJ2).forEach( s => OBJ1.filter(d => d.projectID === s) 

我尝试使用reduce来映射这两个对象,但没有成功。想要的结果是:

Desired Result : 
0: {projectID: 1234, prop1: ["apple","gen"], prop2:["banana","home"], prop3:["choc","home"], 
1:{propjectID:8765, prop1:["apple","gone"], prop2:["banan","done"], prop3:["choc","say"]

非常感谢任何帮助!

javascript arrays object reduce
1个回答
0
投票

您的 JSON 对象是错误的,我已经更正了 JSON 对象,假设这是您想要的请参阅更正后的 JSON 的代码:

function mergeObjects(originalArray, additionalData) {
  return originalArray.map(item => {
    const projectId = item.projectID;
    const additionalProps = additionalData[projectId];

    return {
      projectID: projectId,
      prop1: [item.prop1, additionalProps.prop1],
      prop2: [item.prop2, additionalProps.prop2],
      prop3: [item.prop3, additionalProps.prop3],
    };
  });
}

// Corrected JSON objects
const originalArray = [
  {
    "projectID": 1234,
    "prop1": "apple",
    "prop2": "banana",
    "prop3": "choc"
  },
  {
    "projectID": 8765,
    "prop1": "apple",
    "prop2": "banana",
    "prop3": "choc"
  }
];

// Corrected object two
const additionalData = {
  "1234": {
    "prop1": "gen",
    "prop2": "home",
    "prop3": "home"
  },
  "8765": {
    "prop1": "gone",
    "prop2": "done",
    "prop3": "say"
  }
};

const result = mergeObjects(originalArray, additionalData);
console.log(JSON.stringify(result));

© www.soinside.com 2019 - 2024. All rights reserved.