[英]How to transform an object to array in Javascript
I need to transform these objects in Javascript:我需要在 Javascript 中转换这些对象:
const tables = [
{
table_name: "Table",
columns: [
{
column_name: 'column_1',
values: [{value: 'data1_c1', other:25}, {value: 'data2_c1', other:25}]
},
{
column_name: 'column_2',
values: [{value: 'data1_c2', other:30}, {value: 'data2_c2', other:30}]
},
{
column_name: 'column_3',
values: [{value: 'data1_c3', other:40}, {value: 'data2_c3', other:40}]
}
]
}
]
to this array到这个数组
result = [['data1_c1, 'data2_c1'], ['data1_c2, 'data2_c2'], ['data1_c3, 'data2_c3']]
Please, I need help with this exercise.拜托,我需要这个练习的帮助。
I was trying with this我正在尝试这个
let result = []
tables.map(table =>(
table.columns.map(column => (
column.values.map(value => (
result.push(value.value)
))
))
))
This could be a simple answer这可能是一个简单的答案
var result = []
table[0].columns.forEach(colum => {
var cols = []
colum.values.forEach(valueObj => cols.push(valueObj.value))
result.push(cols)
})
If you have only one item in the tables
array, you can use如果
tables
数组中只有一项,则可以使用
const result = tables[0].columns.map((column) => {
return column.values.map((item) => item.value)
})
If you have multiple items, it is a bit more complex:如果你有多个项目,那就有点复杂了:
const result = tables.reduce((acc, table) => {
return acc.concat(
table.columns.map(column => {
return column.values.map(item => item.value);
})
);
}, []);
const tables = [ { table_name: "Table", columns: [ { column_name: "column_1", values: [ { value: "data1_c1", other: 25 }, { value: "data2_c1", other: 25 } ] }, { column_name: "column_2", values: [ { value: "data1_c2", other: 30 }, { value: "data2_c2", other:30 } ] }, { column_name: "column_3", values: [ { value: "data1_c3", other: 40 }, { value: "data2_c3", other: 40 } ] } ] } ]; const result1 = tables[0].columns.map((column) => { return column.values.map((item) => item.value) }) console.log(result1); const result2 = tables.reduce((acc, table) => { return acc.concat( table.columns.map(column => { return column.values.map(item => item.value); }) ); }, []); console.log(result2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.