2017-04-05 221 views
4

我有這個數組:如何基於另一個對象數組創建一個對象數組?

var arr1 = [ 
{"user":"dan","liked":"yes","age":"22"}, 
{"user":"sarah","liked":"no","age":"21"}, 
{"user":"john","liked":"yes","age":"23"}, 
]; 

我想創建數組的新(子)陣列,只包含用戶的喜歡。

所以它看起來像這樣:

var arr2 = [ 
{"dan":"yes"}, 
{"sarah":"no"}, 
{"john":"yes"}, 
]; 

我想:

var arr2 =[]; 
for(var i in arr1){ 
    arr2.push({[i[user]]:i[liked]}); 
} 

它需要一個調整, 想法?

回答

9

使用array.map

var arr1 = [ 
 
{"user":"dan","liked":"yes","age":"22"}, 
 
{"user":"sarah","liked":"no","age":"21"}, 
 
{"user":"john","liked":"yes","age":"23"}, 
 
]; 
 

 
var arr2 = arr1.map(v => ({ user: v.user, liked: v.liked })); 
 

 
console.log(arr2);

有了您的更新,但它可以與array.map做,我建議你使用一個鍵值對結構,而不是。你需要array.reduce

var arr1 = [ 
 
    {"user":"dan","liked":"yes","age":"22"}, 
 
    {"user":"sarah","liked":"no","age":"21"}, 
 
    {"user":"john","liked":"yes","age":"23"}, 
 
    ]; 
 

 
    var arr2 = arr1.reduce((c, v) => (c[v.user] = v.liked, c) , {}); 
 

 
    console.log(arr2);

+0

我在我的問題犯了一個錯誤!編輯!對不起 – Ted

2

根據您的編輯:

arr1 = arr1.map(function(item){ 
 
    return{ 
 
    [item.user]: item.liked 
 
    } 
 
});

0

您可以映射解構希望屬性的新對象。

var array1 = [{ user: "dan", liked: "yes", age: "22" }, { user: "sarah", liked: "no", age: "21" }, { user: "john", liked: "yes", age: "23" }], 
 
    array2 = array1.map(({ user, liked }) => ({ [user]: liked })); 
 

 
console.log(array2);

ES5

var array1 = [{ user: "dan", liked: "yes", age: "22" }, { user: "sarah", liked: "no", age: "21" }, { user: "john", liked: "yes", age: "23" }], 
 
    array2 = array1.map(function (o) { 
 
     var temp = {}; 
 
     temp[o.user] = o.liked; 
 
     return temp; 
 
    }); 
 

 
console.log(array2);

1

試試這個

var arr2 =[]; 
for(var i in arr1){ 
    var obj= {}; 
    obj[arr1[i]['user']] = arr1[i]['liked']; 
    arr2.push(obj) 
} 
2

var arr1 = [ 
 
{"user":"dan","liked":"yes","age":"22"}, 
 
{"user":"sarah","liked":"no","age":"21"}, 
 
{"user":"john","liked":"yes","age":"23"}, 
 
]; 
 

 
var res = arr1.map(function(o) { 
 
    var r = {}; 
 
    r[o.user] = o.liked; 
 
    return r; 
 
}); 
 

 
console.log(res);

或者在最近的ECMAScript版本:

var arr1 = [ 
 
{"user":"dan","liked":"yes","age":"22"}, 
 
{"user":"sarah","liked":"no","age":"21"}, 
 
{"user":"john","liked":"yes","age":"23"}, 
 
]; 
 

 
var res = arr1.map(o => ({ [o.user]: o.liked })); 
 

 
console.log(res);

1
var arr2=[]; 
arr1.forEach(function(obj) 
{ 
    var temp=new Object(); 
    temp[obj.user]=obj.liked; 
    arr2.push(temp); 
}); 

我想這是你想要的

相關問題