0

I have a object like this :

totalProduct = [{name: "A", string: "Hello"}, {name: "A", string: "Hello"}, {name: "B", string: "Hey"}]; 

I calculate the total of the same name. So far everything is fine, I did this :

let counts = {}; for (const i in totalProduct) { const nameObject = totalProduct[i].name; const stringObject = totalProduct[i].string; counts[nameObject] = (counts[nameObject]||0) + 1; } 

The output is this :

{A:2, B:1} 

BUT, i would like to have this output (Put the object value inside of an array with a string), but i don't know how to do this :(

{A:[2, 'Hello'], B:[1, 'Hey']} 

I'have tried to do this but it's not working :

let counts = {}; for (const i in totalProduct) { const nameObject = totalProduct[i].name; const stringObject = totalProduct[i].string; counts[nameObject] = [(counts[nameObject]||0) + 1, stringObject]; } 
6
  • 1
    From where these string objects came from? Commented Feb 23, 2021 at 18:04
  • That is, the Hello and Hey, where do they originate? Commented Feb 23, 2021 at 18:05
  • The Hello and Hey come from const stringObject = totalProduct[i].string; Commented Feb 23, 2021 at 18:07
  • totalProduct = [{name: "A"}, {name: "A"}, {name: "B"}]; this does not have a property string Commented Feb 23, 2021 at 18:10
  • for every object with value A on its name property, they will also have the same string value? Could there be { name : 'A', string: 'Hello' } and { name : 'A', string: 'Hey' } ? Commented Feb 23, 2021 at 18:10

2 Answers 2

1

You need to set counts[nameObject] to an array of two elements

const totalProduct = [{name: "A", string: "Hello"}, {name: "A", string: "Hello"}, {name: "B", string: "Hey"}]; let counts = {}; for (const i in totalProduct) { const nameObject = totalProduct[i].name; const stringObject = totalProduct[i].string; const prevObj = counts[nameObject] counts[nameObject] = [(prevObj ? prevObj[0] : 0) + 1, stringObject]; } console.log(counts);

Sign up to request clarification or add additional context in comments.

Comments

1

When iterating over the array, instead of putting just the count as the value in the object, put the [number, string] array (like your desired object) onto the object. On each iteration, create the array inside the object if the property doesn't exist yet, and then increment the [0]th item in the array regardless:

const arr = [{name: "A", string: 'Hello'}, {name: "A", string: 'Hello'}, {name: "B", string: 'Hey'}]; const obj = {}; for (const { name, string } of arr) { if (!obj[name]) obj[name] = [0, string]; obj[name][0]++; } console.log(obj);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.