JS数组:如何比较两个并创建第三个

时间:2018-04-21 10:15:37

标签: javascript arrays

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

拜托,您能就此提出建议:

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

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"]
};

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

提前谢谢!

3 个答案:

答案 0 :(得分:2)

使用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);




答案 1 :(得分:0)

或许你需要this:键值数组:

var myArray = {"itemid3": "13.40", "itemid8": "400", "itemid9": "500"};

你添加这样的新项目:

myArray = [];
myArray.itemid15 = "300";

答案 2 :(得分:0)

使用数组缩减功能



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 newObject = selectItems.reduce(function(acc, curr, index) {
  // acc is the object passes as an argument
  // curr is current element
  // in this case curr will be "itemid3", "itemid8", "itemid9" ..so on
  acc.itemId.push(curr);
  // in next step get the index of the itemId3 etc from the original array
   // use this index to get the value from activeItems .price
  acc.price.push(activeItems.price[activeItems.itemId.indexOf(curr)])
  return acc;

}, {

  itemId: [],
  price: []
});
console.log(newObject)