Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create an array of objects based on another array of objects?

Tags:

javascript

I have this array:

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

I'd like to create a new (sub)array of that array, containing only the likes of the users.

so it would look like this:

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

I tried:

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

it needs a tweak, ideas?

like image 722
Ted Avatar asked Apr 05 '17 13:04

Ted


Video Answer


1 Answers

Use 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);

With your update, although it can be done with array.map, I recommend you use a key-value pair structure instead. You'd need 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);
like image 127
Joseph Avatar answered Sep 28 '22 09:09

Joseph