Reputation: 125
I have an array of an object with dynamic keys
response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];
I want to flatten this array of an object into a single array
Output = [1, 1, 1, 0, 0]
I tried the following:
const test2 = this.response.map(obj => {
Object.keys(obj).map(function(key){
return obj[key]
})
});
const test = this.response.reduce(function(prev, curr){
console.log(curr)
return (curr) ? prev.concat(curr): prev;
},[]);
Upvotes: 3
Views: 262
Reputation: 2340
response = [{"1": 1},{"2": 1},{"3": 1},{"4": 0},{"5": 0}]
var newArray = []
for (element of response) {
Object.keys(element).map(key => {
newArray.push(element[key])
})
}
console.log(newArray)
Upvotes: 1
Reputation: 50291
Use reduce and for..in
to loop over the object
let response = [{
"1": 1
},
{
"2": 1
},
{
"3": 1
},
{
"4": 0
},
{
"5": 0
}
]
let k = response.reduce(function(acc, curr) {
for (let keys in curr) {
acc.push(curr[keys])
}
return acc;
}, [])
console.log(k)
Upvotes: 1
Reputation: 39322
You can use .map()
with .concat()
:
let data = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];
let result = [].concat(...data.map(Object.values));
console.log(result);
Upvotes: 5
Reputation: 207501
You can just use map and object.values
response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}]
const vals = response.map(o => Object.values(o)[0])
console.log(vals)
Upvotes: 7