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

IT技术 javascript ecmascript-6 javascript-objects
2021-03-17 09:19:54
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个回答

您可以使用mapObject.values

let array = json.map(obj => Object.values(obj));
Object.values 虽然不是 ES6。
2021-05-04 09:19:54

您可以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);

Object.values 对我来说更有用!谢谢
2021-04-22 09:19:54
同样在这里:Object.values不是 ES6。可能很好用,但由于 OP 只提到 ES2015,至少值得指出。
2021-05-01 09:19:54

如果您需要明确指定顺序,您可以解构和映射每个项目:

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" }]

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

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