1

How to map array into object in JavaScript? For example how to map this

{
  name: [1,2,3,4,5,6],
  uv: [300,-145,-100,-8,100,9],
  pv: [456,230,345,450,312,235]
}

into this

data = [
  {name: '1', uv: 300, pv: 456},
  {name: '2', uv: -145, pv: 230},
  {name: '3', uv: -100, pv: 345},
  {name: '4', uv: -8, pv: 450},
  {name: '5', uv: 100, pv: 321},
  {name: '6', uv: 9, pv: 235}
]

in JavaScript

2

3 Answers 3

2

You can use array#map

var obj = {
 name:[1,2,3,4,5,6],
 uv:[300,-145,-100,-8,100,9],
 pv:[456,230,345,450,312,235]
};

var result = obj.name.map(function(v,i){
  return {name: v, uv: obj.uv[i], pv: obj.pv[i]};
});

console.log(result);

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

Comments

0

Somehow like this:

var first = {
 name:[1,2,3,4,5,6],
 uv:[300,-145,-100,-8,100,9],
 pv:[456,230,345,450,312,235]
}

var data = [];

first.name.forEach((item, i) => {
  data.push({
    name: first.name[i],
    uv: first.uv[i],
    pv: first.pv[i]
  })
})

console.log(data)

3 Comments

This will only work when length of name, uv and pv is same. Else we will start getting undefined.
@TavishAggarwal, yes, but in OP question they have the same length, I wrote this code based on OP's question. If they will have different length, we need to write another code.
Yes. True! But its better to give generalize approach.. :-D
0

You could iterate the keys and then the properties and assign at each index the wanted values.

This works with an arbitrary count of properties without knowing in advance.

var data = { name: [1, 2, 3, 4, 5, 6], uv: [300, -145, -100, -8, 100, 9], pv: [456, 230, 345, 450, 312, 235] },
    result = Object
        .keys(data)
        .reduce((r, k) => (data[k].forEach((v, i) => (r[i] = r[i] || {})[k] = v), r), []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.