简体   繁体   中英

reducing key values of an array

I have an array like

var myArray = [{ques: 1, ans: "A"}, 
               {ques: 2, ans: "D"}, 
               {ques: 3, ans: "C"}];

I want to convert it as a new array like:

var newArray= [{1: "A"}, {2: "D"}, {3: "C"}]

Please help me to achieve it.

UPDATE I have realized that working with newArray is really difficult.OOPS! it would be meaningful to convert it to

var newArray=[1: "A", 2: "D", 3: "C"]

Please help me in it.

Array.prototype.map() function should do the job:

 var myArray = [{ques: 1, ans: "A"}, {ques: 2, ans: "D"}, {ques: 3, ans: "C"}], newArr = myArray.map(function (o) { var newObj = {}; newObj[o.ques] = o.ans; return newObj; }); console.log(newArr); 

Use map function

const mappedArr = myArray.map(elem => {
    return {[elem.ques] : elem.ans};
})

You could use Array#map with a computed property .

 var myArray = [{ ques: 1, ans: "A" }, { ques: 2, ans: "D" }, { ques: 3, ans: "C" }], newArray = myArray.map(a => ({ [a.ques]: a.ans })); console.log(newArray); 

Use map to transform each element of the array:

var myArray = [ {ques: 1, ans: "A"}, 
                {ques: 2, ans: "D"}, 
                {ques: 3, ans: "C"}];

var newArray = myArray.map(function(it) { 
    var ret = {};
    ret[it.ques] = it.ans;
    return ret; 
});

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