-1

I have a data object like this:

{
  "backgroundColor": [
    "#E5700F",
    "#DA830F",
  ],
  "data": [
    26,
    10,
  ],
}

I want to change the format to be like this:

[
{
"backgroundColor": "#E5700F",
"data": 26,},
{
"backgroundColor": "#DA830F",
"data": 10,},
]

how to achieve it using javascript?

1

3 Answers 3

1

You could do this:

const old = {
  backgroundColor: ["#E5700F", "#DA830F"],
  data: [26, 10],
};

let newArray = [];

old.backgroundColor.forEach((item, idx) => {
  newArray.push({ backgroundColor: item, data: old.data[idx] });
});

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

Comments

0

This could work if the object is not dynamic.

let data = {
  "backgroundColor": [
    "#E5700F",
    "#DA830F",
  ],
  "data": [
    26,
    10,
  ],
};

let result = data.backgroundColor.map(function(item, index) {
  return {
    backgroundColor: item,
    data: data.data[index]
  }
});

console.log(result);

Comments

0

You can do it like this: Note that the array's length may not be equal, so it is best to consider this in your data conversion routine.

let sourceData = {
    "backgroundColor": [
        "#E5700F",
        "#DA830F",
    ],
    "data": [
        26,
        10,
    ],
};

let result = [];
let length = Math.max(sourceData.backgroundColor.length, sourceData.data.length);

for (let index = 0; index < length; index++) {
    result.push({
        "backgroundColor": sourceData.backgroundColor[index],
        "data": sourceData.data[index]
    })
}

console.log(result);

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.