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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With