Lodash向对象添加属性的方式

时间:2016-12-13 10:56:15

标签: javascript lodash

我有一个对象

{ id1: {name: 'John'}, id2: {name: 'Mary'} }

我需要assign每个人的财产。我需要实现这个

{ id1: {name: 'John', married: false}, id2: {name: 'Mary', married: false} }

我可以forEach通过_.values来完成,但它似乎不是最好的方法。是否有 LoDash 方法来执行此操作

3 个答案:

答案 0 :(得分:3)

使用var obj = { id1: {name: 'John'}, id2: {name: 'Mary'} } for (let [key, val] of Object.entries(obj)) val.married = false console.log(obj)

_.mapValues

防止原始数据的突变

var res = _.mapValues(data, function(val, key) {
    val.married = false;
    return val;
})

到位突变

var res = _.mapValues(data, function(val, key) {
    return _.merge({}, val, {married: false});
})

答案 1 :(得分:0)

ES6版本,可能也是最快的......?



public class Device : TableEntity
 {
   public Device(string partitionKey, string rowKey)
     {
        this.PartitionKey = partitionKey;
        this.RowKey = rowKey;
     }

      public Device() { }

      public string DeviceName { get; set; }

      public string DeviceOS { get; set; }

      public string Make { get; set; }
 }




答案 2 :(得分:0)

使用_.mapValues

    let rows = { id1: {name: 'John'}, id2: {name: 'Mary'} };

    _.mapValues(rows, (value, key) => {
        value.married = false;
    });

输出:-

{id1: {name: "John", married: false}, id2: {name: "Mary", married: false}}