合并嵌套对象而不会发生变化 [英] Merge nested objects without mutating

查看:99
本文介绍了合并嵌套对象而不会发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2个JavaScript对象:

I have the following 2 JavaScript Objects:

let o1 = {
  entities: {
    1: {
      text: "fooo",
      nested: {
        ids: [1, 2, 3],
        flag: true
      }
    }
  }
};

let o2 = {
  ids: [4, 5, 6]
}

我想合并它们而不对其进行突变,以获得一个看起来像这样的对象:

I want to merge them without mutating them, to get an Object which looks like this:

let o3 = {
  entities: {
    1: {
      text: "fooo",
      nested: {
        ids: [1, 2, 3, 4, 5, 6],
        flag: true
      }
    }
  }
};

可能有n个entities,但是只有entityId定义的一个会受到影响. 我尝试过的:

There could be n entities, but only the one defined by entityId should be affected. What I tried:

let entityId = 1;

let o3 = Object.assign({}, o1, {
         entities: Object.assign({}, o1.entities, {
           [entityId]: Object.assign({}, o1.entities[entityId].nested,
            { ids: [...o1.entities[entityId].nested.ids, ...o2.ids] }
          )
        })
      });

问题在于text: "fooo",nested:完全消失了.

我的方法是对的吗?可以优化此代码吗?

Is my aproach right? Could this code be optimized?

推荐答案

由于您标记了Redux,所以我假设您正在使用React,并建议您使用不可变性帮助程序-

Since you tagged Redux, I will assume you are using React and suggest you use the immutability helper - https://facebook.github.io/react/docs/update.html

您的代码如下:

let o3 = update(o1, {
    entities: {
        [entityId]: {
            nested: {
                ids: {
                    $push: [4, 5, 6]
                }
            }
        }
    }
})


ES6

您的逻辑是正确的,但是您在代码中缺少了nested对象:

Your logic is correct, but you are missing the nested object in your code:

let o3 = Object.assign({}, o1, {
     entities: Object.assign({}, o1.entities, {
       [entityId]: Object.assign({}, o1.entities[entityId], { 
          nested : Object.assign({}, o1.entities[entityId].nested ,{
            ids: [...o1.entities[entityId].nested.ids, ...o2.ids] }) 
        }
      )
    })
  });

这篇关于合并嵌套对象而不会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆