【问题标题】:add parent key to array of objects using lodash使用 lodash 将父键添加到对象数组
【发布时间】:2016-10-02 10:19:58
【问题描述】:

你好,我的朋友们, 我正在寻找从这个转换对象数组res

[{
    "Key1": 1,
    "Key2": "James",
},
{
    "Key1: 2,
    "Key2": "John",
}]

对此(基本上为数组中的每个对象添加一个父键):

[{"ParentKey":
   {
    "Key1" : 1,
    "Key2" : James"
   }
  },
 {"ParentKey":
   {
    "Key1" : 2,
    "Key2" : "John"
   }
 }]

可能不使用蛮力方法(for 循环),但可能是 lodash?

非常感谢

【问题讨论】:

    标签: javascript arrays object lodash


    【解决方案1】:

    使用map 转换数组中的每个元素。

    _.map([
        {"Key1": 1,"Key2": "James",},
        {"Key1": 2,"Key2": "John",}], 
        function(v) {
            return {"ParentKey":v}
        })
    

    【讨论】:

      【解决方案2】:

      使用纯 Javascript,您可以使用 Array#forEach 进行迭代并分配一个新对象。

      var res = [{ Key1: 1, Key2: "James", }, { Key1: 2, Key2: "John", }];
      
      res.forEach(function (a, i, aa) {
          aa[i] = { ParentKey: a };
      });
      
      console.log(res);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      作为替代方案,您可以使用 Array#map 进行迭代并将结果数组分配给一个变量。

      var res = [{ Key1: 1, Key2: "James", }, { Key1: 2, Key2: "John", }],
          padded = res.map(function (a) {
              return { ParentKey: a };
          });
      
      console.log(padded);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案3】:

        您可以简单地使用Array.map function 来获得所需的结果。

        这里是sn-p。

        var array = [{"Key1": 1,"Key2": "James",}, {"Key1": 2,"Key2": "John",}];
        var result = array.map(function(item){
          return {"parentKey": item};
        });
        
        console.log(result);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-20
          • 2023-01-19
          • 1970-01-01
          • 2019-05-07
          • 2018-11-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多