减少数组的键值

时间:2017-01-31 14:46:35

标签: javascript

我有一个类似

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

我想将其转换为新数组,如:

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

请帮助我实现它。

更新 我意识到使用newArray真的很难。很多! 将它转换为

是有意义的
var newArray=[1: "A", 2: "D", 3: "C"]

请帮助我。

4 个答案:

答案 0 :(得分:4)

Array.prototype.map()函数应该完成这项工作:

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

答案 1 :(得分:3)

使用map功能

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

答案 2 :(得分:2)

您可以将Array#mapcomputed 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);

答案 3 :(得分:0)

使用map转换数组的每个元素:

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