Reputation: 63
I want to convert multiple objects with same id as test to array of objects
Actual:
const array= [
{ "test": 1},
{ "test": 2},
{ "test": 3},
{ "test": 4},
]
Expected:
test: [1,2,3,4]
Can someone please help
Upvotes: 0
Views: 86
Reputation: 24638
const arr = [
{ "test": 1 },
{ "test": 2 },
{ "test": 3 },
{ "test": 4 },
{ "test1": 1 },
{ "test1": 5 },
{ "test2": 6 }
];
const newArr = arr.reduce((acc, cur) => ({
...acc,
[Object.keys(cur)[0]]: (acc[Object.keys(cur)[0]] || []).concat(Object.values(cur)[0])
}), {});
console.log( newArr );
//{ "test": [1,2,3,4], "test1": [1,5], "test2": [6] }
Upvotes: 0
Reputation: 386540
You could map the values from the object.
const
array = [{ test: 1 }, { test: 2 }, { test: 3 }, { test: 4 }],
values = array.flatMap(Object.values);
console.log(values);
Upvotes: 0
Reputation: 949
Just use the native method map (read more here or here) like this:
const array= [
{ "test": 1},
{ "test": 2},
{ "test": 3},
{ "test": 4},
];
const newArray = array.map(p => p.test);
console.log(JSON.stringify(newArray)); //[1,2,3,4]
Hope this helps.. ;D
Upvotes: 1
Reputation: 3830
const result = {};
yourArray.forEach( ( object ) => {
const keys = Object.keys( object );
for ( let i = 0; i < keys.length; i++ ) {
const key = keys[ i ];
if ( ! key in result ) {
result[ key ] = [];
}
result[key] = [...result[key], ...object[key] ];
}
});
console.log( result );
In this case:
Upvotes: 0
Reputation: 3178
You can use the map function for this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map :
const newarray = array.map(x => x.test);
console.log(newarray);
Upvotes: 0