Home > OS >  Convert an object containing more objects into an array
Convert an object containing more objects into an array

Time:02-19

This is what I am working with:

let object = {
  'A':{
    "a": {
        "1": "2",
        "3": "4"},
    "b": {
        "3": "4",
        "5": "6"}
    },
  'B':{
    "c": {
        "7": "8",
        "9": "10"},
    "d": {
        "11": "12",
        "13": "14"}
    }
}

I have been trying to compute my output result to look like this

result = [ 
    {"a": {"1": "2", "3": "4"}},
    {"b": {"3": "4", "5": "6"}},
    {"c": {"7": "8", "9": "10"}}
    {"d": {"11": "12", "13": "14"}}
]

I have tried the following which is closer but not the same as what I am looking for: Object.entries(object).map(([key, value]) => { return value })

CodePudding user response:

Can be done using 2 forEach

let object = {
  'A':{
    "a": {
        "1": "2",
        "3": "4"},
    "b": {
        "3": "4",
        "5": "6"}
    },
  'B':{
    "c": {
        "7": "8",
        "9": "10"},
    "d": {
        "11": "12",
        "13": "14"}
    }
}



let res = []
Object.values(object).forEach((value) => {
    Object.entries(value).forEach((el) => {
    res.push({[el[0]]: el[1]})
  })
})


console.log(res)

CodePudding user response:

Try this

let object = {
  'A':{
    "a": {"1": "2", "3": "4"},
    "b": {"3": "4", "5": "6"}
  },
  'B':{
    "c": {"7": "8", "9": "10"},
    "d": {"11": "12", "13": "14"}
  }
};

let arr = Object.entries(Object.assign({}, ...Object.values(object))).map(([k, v]) => ({[k]: v}));
console.log(arr)

CodePudding user response:

Try this:

Object.values(object)
    .flatMap(a => Object.entries(a))
    .map(([k, v]) => ({ [k]: v }))

Edited to use the last map idea from @Thomas instead of using Object.fromEntries

  • Related