Er Ekta Sahu
Er Ekta Sahu

Reputation: 363

How to convert object all value to number of object

I have a object and i want to convert it to be like number of objects

see this is a object -

[{
    "type_width": "245",
    "type_height": "60",
    "type_size": "21"
}]

and want to convert this object like:

[{ "Type Width": "245"},{"Type Height": "60"},{"Type Size": "21"}]

Upvotes: 2

Views: 1250

Answers (3)

vdegenne
vdegenne

Reputation: 13270

If it's in a variable already :

let obj = [{
  width: "245",
  height: "60",
  size: "21"
}]
    
console.log(
  Object.keys(obj[0]).map(k => ({[k] : obj[0][k]}))
)

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191986

You can use Array.flatMap() to iterate the objects, and flatten the results to a single array. Convert each object to an array of key/value pairs with Object.entries(), and Array.map() the pairs to an object.

const data = [{"width":"245","height":"60","size":"21"}]
    
const result = data.flatMap(o => // iterate the objects and merge the results to a single array
  Object.entries(o) // convert each object to an array of key/value pairs
  .map(([k, v]) => ({ [k]: v })) // convert each pair to an object
)
  
console.log(result)

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can use Object.entries and map

let arr = [{ "width": "245","height": "60","size": "21"}]
    
let op = Object.entries(arr[0]).map(([key,value]) => ({[key]: value}) )

console.log(op)

Upvotes: 3

Related Questions