Set same key for all values in array

Viewed 44

I have:

const fruit = ["Apple", "Orange", "Peer"]
const rank = ["1", "2", "3"]

If I do:

const values = [{
"fruit" : fruit,
"rank" : rank
]}

I get

values = [{
{"fruit": ["Apple", "Orange", "Peer"]},
{"rank": ["1", "2", "3"]}
}] 

What should I do to get the data in the below format?

values = [
    { fruit: "Apple", rank : "1"},
    { fruit: "Orange", rank : "2"},
    { fruit: "Peer", rank : "3"},
];
4 Answers

Easiest thing is to use map and loop over one array and create the objects

const fruit = ["Apple", "Orange", "Peer"]
const rank = ["1", "2", "3"]

const result = fruit.map(function(value, index) {
  return { fruit: value, rank: rank[index] };
});

console.log(result);

or

const fruit = ["Apple", "Orange", "Peer"]
const rank = ["1", "2", "3"]

const result = fruit.map((fruit, index) => ({ fruit, rank: rank[index] }))

console.log(result);

You could use Array.prototype.map() method to get the result. Traverse the array using map method and make your required object.

const fruit = ['Apple', 'Orange', 'Peer'];
const rank = ['1', '2', '3'];
const ret = fruit.map((x, i) => ({ fruit: x, rank: rank[i] }));
console.log(ret);

You can map the array with an index:

const fruit = ["Apple", "Orange", "Peer"]
const rank = ["1", "2", "3"]

console.log(fruit.map((f, i) => ({fruit: f, rank: rank[i]})))
.as-console-wrapper {min-height: 100%;}

Another approach with an object of the wanted keys and values.

const
    fruit = ["Apple", "Orange", "Peer"],
    rank = ["1", "2", "3"],
    result = Object
        .entries({ fruit, rank })
        .reduce((r, [k, a]) => a.map((v, i) => ({ ...r[i], [k]: v })), {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related