简体   繁体   English

如何将map对象列表转化为arrays数组

[英]How to map a list of objects into an array of arrays

I have an array of objects that I need to reformat into a list of arrays in a specific format.我有一个对象数组,需要将其重新格式化为特定格式的 arrays 列表。

I need my list to be formatted like this我需要像这样格式化我的列表

list: [
        [ "B", "A" ],
        [ "F", "E" ],
    ]

But the closest I have come is this但我最接近的是这个

list: ["B A", "F E"]

using this code使用此代码

const itemList = [
    {"ProductName":"A",
        "Sku":"B",},
    {"ProductName":"E",
        "Sku":"F",}
];

const newList = itemList.map(item => `${item.Sku} ${item.ProductName}`);

console.log(newList);

How would I map this correctly?我怎么会map这个正确?

You can create array with the values inside map:您可以使用 map 中的值创建数组:

 const itemList = [ {"ProductName":"A", "Sku":"B",}, {"ProductName":"E", "Sku":"F",} ]; const newList = itemList.map(item => [item.Sku, item.ProductName]); console.log(newList);

You can also use destucure for each item and map it to array of these values:您还可以对每个项目使用 destucure 并将其 map 用于这些值的数组:

 const itemList = [ { ProductName: 'A', Sku: 'B' }, { ProductName: 'E', Sku: 'F' } ]; const newList = itemList.map(({ProductName, Sku}) => [ Sku, ProductName ]); console.log(newList);

To keep things simple, I would use Object.values as such:为了简单起见,我将使用 Object.values 如下:

const newList = [];
itemList.map(item => newList.push(Object.values(item)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM