gpt4 book ai didi

javascript - JS 数组 : how to compare two and create third

转载 作者:行者123 更新时间:2023-11-29 20:54:34 26 4
gpt4 key购买 nike

这是我在这里的第一篇文章:-)

拜托,你能就此提出建议吗:

我有一个对象和一个数组:

activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50", "22.10", "13.40", "11", "1100", "500", "100", "400", "500", "20"]
};
selectItems = ["itemid3", "itemid8", "itemid9"];

在 activeItems 对象中,price[0] 表示 itemId[0] 的价格。

所有价格均按正确顺序表示所有商品 ID 的价格。

现在,我想为 selecteItems 数组创建一个包含价格的新对象。

它应该是这样的:

newObject = {
itemId: ["itemid3","itemid8","itemid9"],
price: ["13.40", "400", "500"]
};

基本上,我正在寻找一个公式来为 activeItems 中的 selectedItems 创建新对象并为它们添加价格数组。

提前致谢!

最佳答案

使用 forEach循环并从 activeItems.itemId 中获取项目索引可用于从activeItems.price中获取相应的价格值.

var activeItems = {
itemId: ["itemid1", "itemid2", "itemid3", "itemid4", "itemid5", "itemid6", "itemid7", "itemid8", "itemid9", "itemid10"],
price: ["10.50","22.10","13.40","11","1100","500","100","400","500","20"]
};

var selectItems = ["itemid3","itemid8","itemid9"];

var itemId = [];
var price = [];
selectItems.forEach(function(item){
var index = activeItems.itemId.indexOf(item);
itemId.push(item);
price.push(activeItems.price[index]);
});

var newObject = {
itemId: itemId,
price : price
};

console.log(newObject);

关于javascript - JS 数组 : how to compare two and create third,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954692/

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