簡體   English   中英

使用 lodash 將父鍵添加到對象數組

[英]add parent key to array of objects using lodash

HOLA我的朋友在那里,我要找對象的數組transfor res從這個:

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

為此(基本上為數組中的每個對象添加一個父鍵):

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

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

非常感謝

使用普通的 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; }

使用map來轉換數組中的每個元素。

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

您可以簡單地使用Array.map function來獲得所需的結果。

這是片段。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM