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