1

Trying to map array of objects with values nested in child objects structure like:

const objs = [{
        "B": {
            "value": 1,
        },
        "D": {
            "value": "45"
        },
        "E": {
            "value": "234"
        },
        "A": {
            "value": "543"
        },
        "C": {
            "value": "250"
        }
    },...]

to the structure like:

[
  { name: 'B', value: 1 }, 
  { name: 'D', value: '45' }, 
  { name: 'E', value: '234' }, 
  { name: 'A', value: '543' },
  { name: 'C', value: '250' }
]

and the result of the mapping is undefined

const mapped = objs.map((key, index) => {
  Object.keys(key).map(el => ({
    name: el
  }))
})

Example: Stackblitz

corry
  • 1,457
  • 7
  • 32
  • 63

3 Answers3

5

You are missing return statement and value property definition.

Besides you may want to use flatMap instead of map in order to avoid a nested array in the result:

const objs = [{
    "B": {
        "value": 1,
    },
    "D": {
        "value": "45"
    },
    "E": {
        "value": "234"
    },
    "A": {
        "value": "543"
    },
    "C": {
        "value": "250"
    }
}]

const mapped = objs.flatMap((key, index) => {
    return Object.keys(key).map(el => ({
        name: el,
        value: key[el].value
    }))
})

console.log(mapped)
antonku
  • 7,377
  • 2
  • 15
  • 21
  • Great example. Is there a way to keep order of the elements through the iteration as in the example? – corry Jul 16 '19 at 12:16
  • Thanks! Is the order of objects in result different from the order of keys? On my side it appear to be the same (B, D, E, A, C). – antonku Jul 16 '19 at 12:29
4

You should operate on objs[0], not objs, because it is an array of one object, not array of objects.

let array = []
for(let object in objs[0]){
array.push({
"name": object,
"value": objs[0][object].value
})
}
Iiskaandar
  • 394
  • 2
  • 7
  • My mistake, I didn't add whole data structure (just three dots), there are array of objects like in the example on the stackblitz. – corry Jul 16 '19 at 12:20
3

return is missing in Object.keys. As well instead of Object.keys use Object.entries to get key and value.

const objs = [{
  "B": {
    "value": 1,
  },
  "D": {
    "value": "45"
  },
  "E": {
    "value": "234"
  },
  "A": {
    "value": "543"
  },
  "C": {
    "value": "250"
  }
}];
const mapped = objs.map((key, _) => {
  return Object.entries((key)).map(([name, {
    value
  }]) => ({
    name,
    value
  }))
}).flat();

console.log(mapped);
random
  • 7,756
  • 3
  • 19
  • 25