2016-10-02 63 views
-1

HOLA我的朋友在那裏, 我期待從這個transfor對象數組res使用添加父鍵對象數組lodash

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

這(基本上將在父鍵每個對象陣列):

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

可能沒有使用bruteforce方法(for循環),但也許lodash?

非常感謝

回答

1

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

0

使用map到陣列中的變換的每個元素。

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

您可以簡單地使用Array.mapfunction來獲得期望的結果。

以下是摘錄。

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

 
console.log(result);