使用lodash使用另一个对象扩展一个对象

时间:2016-03-21 10:51:04

标签: lodash

我有一个带有图像数组的对象(只有ids)。

   var listOfImages = {
      "number-items": 30,
      "pageCount": 0,
      "ids": {
        0: "image1",
        1: "image2"
      }
    };

我还有一组图片:

    var images = {
      "image1": {
        "author": "Marc",
        "size": "40kb"
      },
      "image2": {
        "author": "Anthony",
        "size": "60kb"
      },
      "image3": {
        "author": "Anthony",
        "size": "60kb"
      }
    }; image2,
    ]

我想把它们全部结合起来,所以有这样的事情:

var extendedListOfImages = {
  "number-items": 30,
  "pageCount": 0,
  "ids": {
    0: {"id": "image1", "author": "Marc", "size": "40kb"},
    1: {"id": "image2", "author": "Anthony", "size": "60kb"}
  }
};

这是我的代码: https://jsbin.com/pamofudisa/edit?html,js,console,output

1 个答案:

答案 0 :(得分:0)

lodash的新手,所以如果可能的话,我会感谢更好的解决方案。 我现在的解决方案:

  var listOfImages = {
  "number-items": 30,
  "pageCount": 0,
  "ids": {
    0: "image1",
    1: "image2"
  }
};
var images = {
  "image1": {
    "author": "Marc",
    "size": "40kb"
  },
  "image2": {
    "author": "Anthony",
    "size": "60kb"
  },
  "image3": {
    "author": "Anthony",
    "size": "60kb"
  }
};

myIds = _.keyBy(listOfImages.ids);
_.map(myIds, function(key, value){
  myIds[key]= images[key];
});
listOfImages.ids=myIds;
console.log(listOfImages);

jsbin中的代码: https://jsbin.com/qesuyewuza/1/edit?html,js,console,output