将对象数组转换为数组数组

时间:2018-05-02 20:52:31

标签: javascript ecmascript-6 javascript-objects

var json = [{one: "text1", two: "text2", three: 3, four: 4},
            {one: "text3", two: "text4", three: 5, four: 6},
            {one: "text5", two: "text7", three: 8, four: 9}]

如何将上面的对象数组转换为下面的数组数组?

var array = [["text1", "text2", 3, 4], 
             ["text3", "text4", 5, 6], 
             ["text5", "text7", 8, 9]]

是否有ES2015功能可以轻松转换?如果不是for循环可能会。

4 个答案:

答案 0 :(得分:8)

您可以使用mapObject.values

let array = json.map(obj => Object.values(obj));

答案 1 :(得分:4)

如果您需要明确指定订单,您可以对每个项目进行解构和映射:

var array = json.map(({ one, two, three, four }) => ([one, two, three, four]))

这也适用于原始对象中的无序键,例如:

var json = [{ two: "text2", one: "text1", three: 3, four: 4 },
            { one: "text3", three: 5, two: "text4", four: 6 },
            { four: 9, two: "text7", three: 8, one: "text5" }]

答案 2 :(得分:3)

您可以直接使用Object.values作为回调,这可以在ES 2017中使用

var array = [{ one: "text1", two: "text2", three: 3, four: 4 }, { one: "text3", two: "text4", three: 5, four: 6 }, { one: "text5", two: "text7", three: 8, four: 9 }],
    result = array.map(Object.values);
                
console.log(result);

经典方法

var array = [{ one: "text1", two: "text2", three: 3, four: 4 }, { one: "text3", two: "text4", three: 5, four: 6 }, { one: "text5", two: "text7", three: 8, four: 9 }],
    result = array.map(o => Object.keys(o).map(k => o[k]));
                
console.log(result);

答案 3 :(得分:0)

您也可以使用此代码片段 -

function convertObjCollToArrColl(json) {
    for (var i = 0, array = []; i < json.length; i++) {
        var el = json[i];
        array.push([el.one, el.two, el.three, el.four]);
    }
    
    return array;
}

convertObjCollToArrColl(json);