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

1
  • 3
    return is missing. Commented Jul 16, 2019 at 11:55

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Great example. Is there a way to keep order of the elements through the iteration as in the example?
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).
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
})
}

1 Comment

My mistake, I didn't add whole data structure (just three dots), there are array of objects like in the example on the stackblitz.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.