Javascript 使用map或reduce将数组转换为记录
我有这个2d阵列Javascript 使用map或reduce将数组转换为记录,javascript,arrays,dictionary,record,reduce,Javascript,Arrays,Dictionary,Record,Reduce,我有这个2d阵列 [["hair",4560],["ringtones",33]] 我想知道如何使用reduce或map将其转换为记录: 我想用它来知道每一行的col有多长 谢谢您可以轻松地使用数组映射,循环遍历数组中的每个项并对其进行解析 let array = [["hair",4560],["ringtones",33]]; let arrayOfObjects = array.map(e => { // The structure as recommended in
[["hair",4560],["ringtones",33]]
我想知道如何使用reduce或map将其转换为记录:
我想用它来知道每一行的col有多长
谢谢您可以轻松地使用数组映射,循环遍历数组中的每个项并对其进行解析
let array = [["hair",4560],["ringtones",33]];
let arrayOfObjects = array.map(e => {
// The structure as recommended in the comments
// If you want the nested structure you originally were wondering about,
// you can change the return line to match that structure
return {product: e[0], price: e[1]};
});
/**
Contents of the arrayOfObjects is:
[
{ product: 'hair', price: 4560 },
{ product: 'ringtones', price: 33 }
]
*/
这个问题有几个问题,值得注意的是,您没有提供解决这个问题的实际尝试或努力,但我对期望的结果表示怀疑。。。
id
对象?(关于产品?)价格是一个只有一个值的数组吗?这似乎有点奇怪。您确定需要记录中的所有嵌套数组和对象吗?为什么不让它成为一个对象数组呢?最好访问id.product、access.price这样的项目。用数组做起来不容易用这种形式输出不是更有意义吗?:[{product:'hair',price:454},{product:'ringtones',price:6000}]
谢谢Daniel
let array = [["hair",4560],["ringtones",33]];
let arrayOfObjects = array.map(e => {
// The structure as recommended in the comments
// If you want the nested structure you originally were wondering about,
// you can change the return line to match that structure
return {product: e[0], price: e[1]};
});
/**
Contents of the arrayOfObjects is:
[
{ product: 'hair', price: 4560 },
{ product: 'ringtones', price: 33 }
]
*/