如何根据另一个对象数组创建一个对象数组?

时间:2017-04-05 13:26:33

标签: javascript

我有这个数组:

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]});
}

它需要调整, 想法?

7 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

根据您的修改:

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

答案 2 :(得分: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);

答案 3 :(得分:1)

试试这个

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

答案 4 :(得分:1)

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

我认为这就是你想要的

答案 5 :(得分: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);




答案 6 :(得分:0)

如果是对象数组

var arr1 = [{},{},..]

并且您必须遍历对象属性,因此您需要这样做

var arr2 =[]



 arr1.forEach(element => {
      var temp = new Object();
      for (var name in element) {
        temp[name] = element[name]
      }
      arr2 .push(temp)
    });

现在您将arr2作为不同于arr1的另一个对象