Ray*_*Ray 3 javascript javascript-objects ecmascript-6
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}]
Run Code Online (Sandbox Code Playgroud)
如何将上面的对象数组转换为下面的数组数组?
var array = [["text1", "text2", 3, 4],
["text3", "text4", 5, 6],
["text5", "text7", 8, 9]]
Run Code Online (Sandbox Code Playgroud)
是否有ES2015功能可以轻松转换?如果不是for循环可能会.
mic*_*ckl 10
你可以使用map和Object.values
let array = json.map(obj => Object.values(obj));
Run Code Online (Sandbox Code Playgroud)
您可以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);Run Code Online (Sandbox Code Playgroud)
经典方法
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);Run Code Online (Sandbox Code Playgroud)
如果您需要明确指定顺序,您可以解构和映射每个项目:
var array = json.map(({ one, two, three, four }) => ([one, two, three, four]))
Run Code Online (Sandbox Code Playgroud)
这也适用于原始对象中的无序键,例如:
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" }]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2442 次 |
| 最近记录: |