0

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

2
  • 3
    What have you tried, and what exactly is the problem with it? Commented Jan 6, 2022 at 19:40
  • Do you try array.map(e => e.test)? Commented Jan 6, 2022 at 19:42

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
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:

  1. You need to iterate in your array
  2. On each iteration you have a new object
  3. From there you iterate in all the keys of that current object
  4. If the key does not exists in your result create a new empty array
  5. Merge the value from the result with the current value of the object.
  6. Values are stored in result.

Comments

0

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

Comments

0

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] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.