Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I assign values to keys when I merge 2 objects with .map()?

I am using .map() to cycle through an object and places some values in to a 2nd object.

I am doing this as such:

function convertGraphItems(name, data) {
  return ({ name, data, type: 'bar', stack: true });
}

var generatedArr = [...dataByAccountName.entries()].map(convertGraphItems);

However, I seem to be unable to assign ‘name’ and ‘data’ to their respective keys.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried return ({ name: name, data: data, type: 'bar', stack: true }); but this does not achieve what I want.

My desired result should look like:

[
    {
        "name": "Savings",
        "data": [
            5474.18,
            114031.26,
            127890.72
        ],
        "type": "bar",
        "stack": true
    }
]

But my current result is:

[
    {
        "name": [
            "Savings",
            [
                5474.18,
                114031.26,
                127890.72
            ]
        ],
        "data": 0,
        "type": "bar",
        "stack": true
    }
]

Would anyone know how I could assign data and name to their respective keys?

EDIT: source array looks like:

[
    {
        "key": "Savings",
        "value": [
            5474.18,
            114031.26,
            127890.72
        ]
    },
]

>Solution :

You are passing convertGraphItems function into map and you are expecting name as key and data as value, but this is not the case here.

In map the first argument is the value and second is the index.
You have to make convertGraphItems compatible so you can pass value externally as:

[...dataByAccountName.entries()].map(([k, v]) => convertGraphItems(k, v))

or

var generatedArr = [...dataByAccountName.entries()].map(function ([k, v]) {
  return convertGraphItems(k, v);
});
const dataByAccountName = [
  {
    key: "Savings",
    value: [5474.18, 114031.26, 127890.72],
  },
];

function convertGraphItems(name, data) {
  return { name, data, type: "bar", stack: true };
}

var generatedArr = [...dataByAccountName.entries()].map(([k, v]) => convertGraphItems(k, v));
console.log(generatedArr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading