gpt4 book ai didi

javascript - 使用标题破坏

转载 作者:行者123 更新时间:2023-12-01 15:39:51 24 4
gpt4 key购买 nike

我已经用破坏回答了几个问题,我只是想把这个更上一层楼

我想在这个例子中不使用reduce,但如果可能的话,我想纯粹破坏

所以数据的第一行包含对象的属性名称,我怎样才能用它来干燥

即我希望

const obj = data.slice(1).map((titles) => ({ titles }) )

或类似的

所以这行得通,但我又错过了一步:

const data = [
["fruits","frozen","fresh","rotten"],
["apples",884,494,494],
["oranges",4848,494,4949],
["kiwi",848,33,33]
]
const titles = data[0]; // not used below but I want to use it
const obj = data.slice(1).map(([fruits,frozen,fresh,rotten]) => ({ fruits,frozen,fresh,rotten }) )
console.log(obj)

最佳答案

您可以映射对象的条目。

const
data = [["fruits", "frozen", "fresh", "rotten"], ["apples", 884, 494, 494], ["oranges", 4848, 494, 4949], ["kiwi", 848, 33, 33]],
mapWith = keys => values => Object.fromEntries(keys.map((k, i) => [k, values[i]])),
getArray = ([keys, ...data]) => data.map(mapWith(keys)),
array = getArray(data);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


旧的更简单的例子

const data = [
["fruits", "frozen", "fresh", "rotten"],
["apples", 884, 494, 494],
["oranges", 4848, 494, 4949],
["kiwi", 848, 33, 33]
]
const titles = data[0];

const obj = data.slice(1).map(
arr => Object.fromEntries(
titles.map(
(t, i) => [t, arr[i]]
)
)
);

console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 使用标题破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62197270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com