gpt4 book ai didi

javascript - 为数组中的所有值设置相同的键

转载 作者:行者123 更新时间:2023-12-03 07:23:40 25 4
gpt4 key购买 nike

我有:

const fruit = ["Apple", "Orange", "Peer"]
const rank = ["1", "2", "3"]

如果我这样做:

const values = [{
"fruit" : fruit,
"rank" : rank
]}

我明白了

values = [{
{"fruit": ["Apple", "Orange", "Peer"]},
{"rank": ["1", "2", "3"]}
}]

我应该如何获取以下格式的数据?

values = [
{ fruit: "Apple", rank : "1"},
{ fruit: "Orange", rank : "2"},
{ fruit: "Peer", rank : "3"},
];

最佳答案

最简单的事情是使用映射并循环一个数组并创建对象

const fruit = ["Apple", "Orange", "Peer"]
const rank = ["1", "2", "3"]

const result = fruit.map(function(value, index) {
return { fruit: value, rank: rank[index] };
});

console.log(result);

const fruit = ["Apple", "Orange", "Peer"]
const rank = ["1", "2", "3"]

const result = fruit.map((fruit, index) => ({ fruit, rank: rank[index] }))

console.log(result);

关于javascript - 为数组中的所有值设置相同的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64808624/

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