简体   繁体   English

如何添加到现有的 object,知道关键,javascript

[英]How to add to existing object, knowing the key, javascript

Lets say I have an array with values假设我有一个包含值的数组

product: [{ 
'product_id': 247
'order_id': 4
}
{ 
'product_id': 245
'order_id': 3
}
{ 
'product_id': 247
'order_id': 3
}]

I have button passing 'product_id' and 'order_id', and every time the button is pressed, I want an object to be something like this, the 'product_id' gets added at the end of the object array accordingly.我有传递“product_id”和“order_id”的按钮,每次按下按钮时,我希望 object 是这样的,“product_id”相应地添加到 object 数组的末尾。

[{4: [247, 247, 247], 3: [247, 245, 247]}]

I have tried using different array methods我尝试过使用不同的数组方法

var productarray = product
  productarray.reduce((order, obj)=> {
    let key = obj['order_id']
      if (!order[key]) {
      order[key] = []
     }
   order[key].push(obj.product_id);
})

but I'm not able to get the result I'm looking for.但我无法得到我正在寻找的结果。 Sorry if this a vague question.对不起,如果这是一个模糊的问题。 Thank you in advance.先感谢您。

Seems you need to collapse by key, but you have a few mistakes in your sample, this should work:似乎您需要按键折叠,但是您的示例中有一些错误,这应该可以:

var products = [{
    'product_id': 247,
    'order_id': 4
},
{
    'product_id': 245,
    'order_id': 3
},
{
    'product_id': 247,
    'order_id': 3
}];

var orders = products.reduce((m, c) => {
    var order = m[c.order_id];
    if (order) {
        order.push(c.product_id);
    } else {
        m[c.order_id] = [c.product_id];
    }
    return m;
}, {});

console.log(orders);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM