NodeJS 如何比较和操作json对象[已关闭]

l2osamch  于 2022-12-18  发布在  Node.js
关注(0)|答案(3)|浏览(143)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
2天前关闭。
Improve this question
我需要比较和操作JSON对象。

第一个对象

let data1 = {
  "id": "111",
  "entity_id": "222",
  "text_id": "333",
  "details": [{
    "value": 1000,
    "comp_id": "444",
    "CompName": "driving"
  }]
}

第二对象

let data2 = [{
  "id": "111",
  "text_id": "333",
  "criteria_type": "TXT",
  "value": 1000,
  "comp": {
    "id": "444",
    "name": "driving"
  }
}, {
  "id": "222",
  "text_id": "444",
  "criteria_type": "TXT",
  "value": 2000,
  "comp": {
    "id": "555",
    "name": "swiming"
  }
}]

有两个对象data1data2。这里,我需要比较data1.details数组与data2数组key =〉data1.details.comp_iddata2.comp.id。如果不匹配,我需要将valueidname推送到data1对象。请帮助我解决此问题。

结果对象

data1将为:

{
  "id": "111",
  "entity_id": "222",
  "text_id": "333", 
  "declaration_details": [{
    "value": 1000,
    "comp_id": "444",
    "CompName": "driving",
  }, {
    "value": 2000,
    "comp_id": "555",
    "CompName": "swiming",
  }]
}

jm81lzqq

jm81lzqq1#

根据预期的结果,难道不需要将data2Map到结果对象的declaration_details吗?

const main = () => {
  const { details, ...rest } = data1;
  const result = {
    ...rest,
    fbp_year: new Date().getUTCFullYear(),
    declaration_details: data2.map(({
      value,
      comp: {
        id: comp_id,
        name: CompName
      }
    }) => ({
      value,
      comp_id,
      CompName
    }))
  };
  console.log(result);
};

const
  data1 = {
    "id": "111",
    "entity_id": "222",
    "text_id": "333",
    "details": [{
      "value": 1000,
      "comp_id": "444",
      "CompName": "driving"
    }]
  },
  data2 = [{
    "id": "111",
    "text_id": "333",
    "criteria_type": "TXT",
    "value": 1000,
    "comp": {
      "id": "444",
      "name": "driving"
    }
  }, {
    "id": "222",
    "text_id": "444",
    "criteria_type": "TXT",
    "value": 2000,
    "comp": {
      "id": "555",
      "name": "swiming"
    }
  }];
  
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }
mhd8tkvw

mhd8tkvw2#

使用filter()data2中查找与comp.id匹配的对象,然后使用map()创建一个新数组,最后将mappedData2数组添加到declaration_details中的data1

let filteredData2 = data2.filter(item => {
  return data1.details.some(detail => detail.comp_id === item.comp.id);
});
let mapData = filteredData2.map(item => {
  return {
    value: item.value,
    comp_id: item.comp.id,
    CompName: item.comp.name
  };
});
f0brbegy

f0brbegy3#

你可以使用JSON.stringify(yourJsonObject)将对象转换成字符串,然后你可以像这样比较它们。areEqual = string1 == string2。确保两个对象的对象属性顺序相同。

相关问题