简体   繁体   中英

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 ] 

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); 

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;
}, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM