使用标题破坏 [英] Destruct using titles
本文介绍了使用标题破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用销毁回答了一些问题,我只想将其带入一个新的水平
I have answered a few questions using destructing, I just want to take this one to the next level
在此示例中,我不想使用reduce而是纯粹的销毁
I want to not use reduce in this example but pure destructing if at all possible
所以数据的第一行包含对象的属性名称,我该如何使用它作为DRY
So the data's first row contains the attribute names of the object, How can I use that to be DRY
ie我希望
const obj = data.slice(1).map((titles) => ({ titles }) )
或类似的
所以这可行,但我又错过了一步:
So this works, but I miss one more step:
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)
推荐答案
您可以映射对象的条目。
You could map the entries for an object.
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; }
这篇关于使用标题破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文