skip to Main Content

I want to add a variable from array of objects and combine them.

Example data :

    const item = [{
                "act": "Q",
                "line": 1,
                "qty": 6,
                "type": 00
},
{
                "act": "Q",
                "line": 1,
                "qty": 6,
                "type": 00
},
{
                "act": "Q",
                "line": 2,
                "qty": 6,
                "type": 00
},
{
                "act": "Q",
                "line": 2,
                "qty": 4,
                "type": 00
}]

I want to check if act is Q and type is 00 then get the output with line and sum of qty for the line.

    [{
                "line": 1,
                "qty": 12,
},
{
                "line": 2,
                "qty": 10,
}]

2

Answers


  1. So basically what you would want to do is use the Array.filter function and set in the parameters to get what you want.

    Something like this

    let a = item.filter(ele => ele.act == "Q" && ele.type == 00);
    
    console.log(a)
    

    the variable a would now contain all your objects, you can iterate it and print whatever you want

    Login or Signup to reply.
  2. for your input:

    const item = [
      { "act": "Q", "line": 1, "qty": 6, "type": 00 },
      { "act": "Q", "line": 1, "qty": 6, "type": 00 },
      { "act": "Q", "line": 2, "qty": 6, "type": 00 },
      { "act": "Q", "line": 2, "qty": 4, "type": 00 }
    ];
    

    To filter by act and type you can use Array.filter() method like this:

    const filteredByActAndType = item.filter(i => i.act === 'Q' && i.type === 00)
    

    then to sum the qty you can use Array.reduce() method like this:

    const reducedArray = filteredByActAndType.reduce((acc, cur) => {
      const line = acc.find(i => i.line === cur.line)
      if (line) {
        line.qty += cur.qty
      } else {
        acc.push({line: cur.line, qty: cur.qty})
      }
      return acc
    }, [])
    

    output will be exact what you need:

    [
        {
            "line": 1,
            "qty": 12
        },
        {
            "line": 2,
            "qty": 10
        }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search