Home > other >  need help extracting values from an array
need help extracting values from an array

Time:01-31

I am trying to get the values from an object but All that I can get back is: xyz = result; to value [object Object]

**Input: **

tempOut = { ID: "7283", qty: 60.52 },
    { ID: "7280", qty: 3.75 },
    { ID: "7283", qty: 16 }

var array = [
    temphours
    ];

var result = [];
array.reduce(function(res, value) {
    if (!res[value.Id]) {
        res[value.Id] = { Id: value.Id, qty: 0 };
        result.push(res[value.Id])
    }
    res[value.Id].qty  = value.qty;
    return res;
}, {});

Expected output:

result = { ID: "7283", qty: 76.52 },
    { ID: "7280", qty: 3.75 }

Final result:

7283, 76.52
7280,3.75

I tried Console.log but it returns:

Error: org.mozilla.javascript.EcmaError: ReferenceError: "Console" is not defined. (threadScript#1)

CodePudding user response:

You need an array for the data and the right property ID for grouping.

Spelling matters in Javascript.

const
    data = [{ ID: "7283", qty: 60.52 }, { ID: "7280", qty: 3.75 }, { ID: "7283", qty: 16 }],
    result = Object.values(data.reduce(function(res, value) {
        if (!res[value.ID]) res[value.ID] = { ID: value.ID, qty: 0 };
        res[value.ID].qty  = value.qty;
        return res;
    }, {}));

console.log(result);

  • Related