1

I have an array like this-

[{a:23},{b:23},{r:2323},{e:99}]

I want to convert this to a new array containing only the object property values like-

[23,23,2323,99]

I have tried all the methods but could not figure out the way. Can anyone suggest me the idea for this please.

2
  • arr.map((o) => Object.values(o)).flat(); or arr.flatMap((o) => Object.values(o)); Though should should show what research you've done and any attempts you've made to solve the problem yourself Commented Aug 16, 2022 at 10:31
  • Does this answer your question? From an array of objects, extract value of a property as array Commented Aug 16, 2022 at 10:52

2 Answers 2

2

Just use .flatMap and Object.values

const data = [{a:23}, {b:23}, {r:2323}, {e:99}];

const result = data.flatMap(Object.values);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

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

2 Comments

Can simply be data.flatMap(Object.values)
@makeitmorehuman That's a great point!
0
let array = [ { a: 23 }, { b: 23 }, { r: 2323 }, { e: 99 } ]
let array1 = []

for (const obj of array) {
  array1.push(obj[Object.keys(obj)[0]])
}

console.log(array1) // [23, 23, 2323, 99]
  • obj[Object.keys(obj)[0]] returns the first property of the object obj (source)

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.