对象之间的值乘以索引

时间:2019-12-02 01:06:38

标签: javascript reactjs

我被卡住了,我有两个物体

对象1

29: {value: 29, price: "145"}
30: {value: 30, price: "160"}

对象2

29: {value: 29, count: 2}
30: {value: 30, count: 3}

我正在尝试将价格乘以同一索引中的计数,我尝试使用Object.assing将对象1的值复制到对象2,然后将同一对象中的值相乘,但是我没有幸运

我试图仅保留一个包含两个元素之和的元素

3 个答案:

答案 0 :(得分:1)

我敢肯定有更好的方法(更具声明性的)来做到这一点,但是从我的头顶上想出了这就是我想出的。 (PS。名称object1object2有点误导,它们都是对象数组)

function getTotals(object1, object2) {
    let finalObject = []
    for (let i = 0; i < object1.length; i++) {
        for (let j = 0; j < object2.length; j++) {
            if (object1[i].value == object2[j].value) {
                const value = object1[i].value;
                const total = object1[i].price * object2[j].count;

                finalObject.push({ value, total });
            }
        }
    }

    return finalObject;
}


输入的结果将是...

let object1 = [
    {value: 29, price: 145},
    {value: 30, price: 160}
]

let object2 = [
    {value: 29, count: 2},
    {value: 30, count: 3}
]

console.log(getTotals(object1, object2));
// Will return
// [{ value: 29, total: 290 }, { value: 30, total: 480 }]

答案 1 :(得分:0)

我解决了问题,将对象存储在数组中,然后在其上进行了映射,然后执行了Reduce()函数,该方法返回数组的唯一值。

  let object1 = [
  {value: 29, price: 145},
  {value: 30, price: 160}
  ]

  let object2 = [
  {value: 29, count: 2},
  {value: 30, count: 3}
  ]

  var objResult1 = []

  {object1.map(price => {
      objResult1.push(price.price);
  })}

  var objResult2 = []

  {object2.map(count => {
    objResult2.push(count.count);
  })}

  var final = (objResult1.reduce(function(r,a,i){return r+a*objResult2[i]},0));

答案 2 :(得分:0)

使用x * 1 = x的数学:

const prices = [{value: 29, price: 145}, {value: 30, price: 160}] 
const counts = [{value: 29, count: 2}, {value: 30, count: 3}]

const totalsObj = [...prices, ...counts].reduce(
  (acc, {value: k, price = 1, count = 1}) => ({
    ...acc, [k]: acc[k] || 1 * price * count
  }), {}
)

const totalsArr = Object.entries(totalsObj).map(
  ([k, v]) => ({ value: k, total: v})
)

console.log(totalsObj)
console.log(totalsArr)