如果条件 (JavaScript ES6),则将一个特定对象 prop 从一个数组移动到另一个

我有 2 个从 2 个不同的 fetch 返回的对象数组


const result1 = [

  {

    name: 'matteo',

    age: 20,

    id: 1,

  },

  {

    name: 'luca',

    age: 24,

    id: 2,

  },

];


const result2 = [

  {

    warnings: 'yes',

    hobby: "tennis",

    id: 1,

  },

  {

    warnings: 'many',

    hobby: "ping pong",

    id: 2,

  },

];

这是我当前的方法,但如果它们具有相同的 id,它将合并从 result2 到 result1 的整个对象


const t = result2.reduce((acc, curr) => {

    acc[curr.id] = curr;

    return acc;

  }, {});


  const d = result1.map((d) =>

    Object.assign(d, t[d.id]) 

  );

目前的结果是:


{

    name: 'matteo',

    age: 20,

    id: 1,

warnings: "yes",

hobby: "tennis"

  },

  {

    name: 'luca',

    age: 24,

    id: 2,

warnings: "many",

hobby: "ping pong"

  },

我只想将 warnings 属性从第二个对象数组移动到第一个对象数组,其中对象 id 相等


期望的输出:


const result3 = [

      {

        name: 'matteo',

        age: 20,

        id: 1,

        warnings: "yes"

      },

      {

        name: 'luca',

        age: 24,

        id: 2,

        warnings: "many"

      },

    ];


慕的地6264312
浏览 91回答 1
1回答

慕工程0101907

您可以使用它map来创建一个新数组,并find获取具有匹配 id 的任何警告:let result1 = [  { id: 1, name: 'a', age: 1 },  { id: 2, name: 'b', age: 2 },  { id: 3, name: 'c', age: 3 },  { id: 4, name: 'd', age: 4 }];let result2 = [  { id: 1, hobby: 'aa', warnings: 'aaa' },  { id: 2, hobby: 'bb', warnings: 'bbb' },  { id: 4, hobby: 'dd', warnings: 'ddd' }];let includeWarnings = (data, warningsArr) => data.map(obj => {    // `w` will be undefined if no matching warning is found  let w = warningsArr.find(warn => warn.id === obj.id);    // Return all the data in `obj`, and the "warnings" property  // of `w` if `w` is defined  return { ...obj, ...(w ? { warnings: w.warnings } : {}) };  });console.log(includeWarnings(result1, result2));请注意,如果您的数据格式是在考虑映射的情况下构建的,那么您的情况可能会更好id:let result1 = {  id1: { name: 'name1', age: 1 },  id2: { name: 'name2', age: 2 },  .  .  .}let result2 = {  id1: { hobby: 'hobby1', warnings: 'warnings1' },  id2: { hobby: 'hobby2', warnings: 'warnings2' },  .  .  .}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript