xakepp35
xakepp35

Reputation: 3222

How to map array of objects to key-values?

In JS, I have an array A = [{k:"a",v:3},{k:"b",v:4}] consisting of objects, defining key-values. I want to generate array B:

let B = 
((A)=>{
    let B=[];
    for(let i of A)
        B[i.k]=i.v;
    return B;
})(A);

So that it maps A's object keys k to B's keys, and values v to its values. Is that achievable more easily, through Array mapreduce functions? Could you help me with correct syntax? SO that B (for our example) would be:

let B = [];
B["a"]=3;
B["b"]=4;
console.log( B );
[ a: 3, b: 4 ] 

Upvotes: 0

Views: 181

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386522

You could take Object.fromEntries with mapped arrays for a key/value pair.

var array = [{ k: "a", v: 3 }, { k: "b", v: 4 }],
    object = Object.fromEntries(array.map(({ k, v }) => [k, v]));

console.log(object);

Upvotes: 1

Bergi
Bergi

Reputation: 664185

You can drop the IIFE and use

const B = {};
for (const {k, v} of A)
    B[k] = v;

A reduce solution is also possible, but less concise:

const B = A.reduce((acc, {k, v}) => {
    acc[k] = v;
    return acc;
}, {});

Upvotes: 1

Related Questions