如何将对象键值从一个数组附加到其他数组?

时间:2017-10-12 11:58:48

标签: javascript arrays object ecmascript-6

我有一个包含多个对象的现有数组。使用间隔我想用另一个数组中的值更新现有数组。请参阅下面的(简化)示例。

我已经成功了:

  1. 将新数组的fan_count值复制到当前数组,键为“fan_count_new”
  2. 如果在New数组中删除或添加了一个对象,则必须对Current数组执行相同的操作。
  3. 到目前为止我可以看到,我可以使用一些es6函数:),如:

    1. object-assign,但如何设置新密钥“fan_count_new”?
    2. 如何遍历数组以进行比较,添加或删除+复制fan_count?
    3. 当前数组:

      [{
          "fan_count": 1234,
          "id": "1234567890",
          "picture": {
              "data": {
                  "url": "https://scontent.xx.fbcdn.net/v/photo.png"
              }
          }
      },
      {
          "fan_count": 4321,
          "id": "09876543210",
          "picture": {
              "data": {
                  "url": "https://scontent.xx.fbcdn.net/v/photo.png"
              }
          }
      }, ...
      ]
      

      新阵列:

      [{
          "fan_count": 1239,
          "picture": {
              "data": {
                  "url": "https://scontent.xx.fbcdn.net/v/photo.png"
              }
          "id": "1234567890"
      },
      {
          "fan_count": 4329,
          "picture": {
              "data": {
                  "url": "https://scontent.xx.fbcdn.net/v/photo.png"
              }
          },
          "id": "09876543210"
      }, ...
      ]]
      

1 个答案:

答案 0 :(得分:0)

您可以使用array.filter删除新数组中不存在的元素,并且可以遍历新数组以更新当前数组中的同一对象:

var currArr = [
    {
        "fan_count": 1234,
        "id": "1234567890",
    },
    {
        "fan_count": 4321,
        "id": "09876543210",
    },
    {
        "fan_count": 4321,
        "id": "09876543215",
    }
];

var newArr = [
    {
        "fan_count": 1234,
        "id": "1234567890"
    },
    {
        "fan_count": 5555,
        "id": "09876543210"
    }
];

currArr = currArr.filter(obj => newArr.some(el => el.id === obj.id));

newArr.forEach(obj => {
    var found = currArr.find(o => o.id === obj.id);
    if (found) {
        found.fan_count_new = obj.fan_count;
    }
});

console.log(currArr);

后来我意识到最好转过来,将cur_Arr形成currArr添加到新的。这是因为它更容易处理新对象,您不必处理已删除的对象。所以,任何人如何寻找这样的东西:

newArr.forEach(obj => {
  var found = currArr.find(o => o.id === obj.id);
  if (found) {
    console.log('found: ', found.fan_count, obj.fan_count)
    obj.fan_count_prev = found.fan_count;
    obj.fan_count_diff = Math.round(obj.fan_count - found.fan_count);
  }

  if (typeof obj.fan_count_prev === "undefined") {
    obj.fan_count_prev = obj.fan_count;
    obj.fan_count_diff = 0
  }
});