简体   繁体   中英

Get an array containing values of dynamic object property from the given array

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.

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 }

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM