Home > Back-end >  How to sum all Object using index with an arrays
How to sum all Object using index with an arrays

Time:02-13

how can I search duplicate data using index key object here is my object :

 const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }

and I have an arrays

const arr = ["product1", "product2" ]

I want to get only product1 and product2 data then sum price together my output shold look like this 4 2 2 = 8

Here is what I try to do

const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum 

    const sum = newArr.reduce((data, obj)=> data   obj.price, 0);

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

 const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }

CodePudding user response:

I would use Array.prototype.reduce to iterate through the array and return a single value that is the total price.

    const products = {
        id1: { name: "paper", price: 4 },
        id2: { name: "ball", price: 2 },
        id3: { name: "ice-cream", price: 9 },
    };

    const productIds = ["id1", "id2"];

    const totalPrice = productIds.reduce((sum, id) => {
        return sum   products[id].price;
    }, 0);

CodePudding user response:

Non lodash implementation. filtered the array and ran reduce

const arr = ["product1", "product2" ]
const obj2 = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 },
        "product1 Hello4": { name: 'paper', price: 2 }
    }
    
 let filtered = Object.entries(obj2).filter((el) => arr.includes(el[0].split(" ")[0]))
 
 const sum = filtered.reduce((acc,curr)=> acc   curr[1].price, 0);
 console.log(sum)

CodePudding user response:

Your problem is that the obj will never contain the key product1 twice. When that object is created during runtime the last value of product1 is what is stored in the object. Even if you had a JSON object with those two keys, when you go to parse it, the last key will be the value. The only way I can think to do what you want is that you need to change the data prior to the object being created.

You added to unique keys, which isn't going to help you as now you'll need to iterate through all the keys to make sure you are getting all of them. You are better off putting the key in the object, and use an array of objects.

const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]

You can then use Array.reduce to combine the values, or other methods.

Now to get only product 1 and 2 use filter:

const desiredProducts = obj.filter(p => ['product1','product2'].includes(p.key));
``

Or you can combine any matching keys using Array.reduce()

```js
const combinedResult = obj.reduce((cur, acc) => {
  const s = cur.find(c => c.key === acc.key);
  if (s)
    s.price  = acc.price;
  else
   cur.push(acc);  

}, []);

CodePudding user response:

JSON object can't hold duplicate keys. If so, it gets replaced by the last record.

In your case, the input becomes:

const obj = {
  product1: { name: 'paper', price: 2 },
  product2: { name: 'ball', price: 2 },
  product3: { name: 'ice-cream', price: 9 }
}

Your possible input will be like thes:

const obj = {
  product1: [{ name: 'paper', price: 4 }, { name: 'paper', price: 2 }],
  product2: [{ name: 'ball', price: 2 }],
  product3: [{ name: 'ice-cream', price: 9 }]
}
const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]

Updated answer as updated code:

const obj = {
  "product1 Hello": {name: 'paper', price: 4},
  "product2 test": {name: 'ball', price: 2},
  "product3 Hello3": {name: 'ice-cream', price: 9},
  "product1 Hello4": {name: 'paper', price: 2}
}
const arr = ["product1", "product2"]

let keys = Object.keys(obj).filter(x => arr.some(y => x.includes(y)))
keys.map(x => obj[x].price).reduce((x, y) => x   y, 0)
  • Related