Home > Software engineering >  Get an array containing values of dynamic object property from the given array
Get an array containing values of dynamic object property from the given array

Time:08-16

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.

CodePudding user response:

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 }

CodePudding user response:

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)
  • Related