0

I'm trying to iterate through objects in an object. I want to only push the properties of the objects into a new array, but only properties with unique hash. I would like to find a solution that will do that inside the for...in.

This solution only pushes the unique hashes, but not the unique "prop.property" objects

for (const prop in this.totals) {
      this.totals[prop].map(prop =>  this.totalProperties.indexOf(prop.property.hash) === -1 ? 
          this.totalProperties.push(prop.property.hash) : null
      );
    }

I tried this other one, but it pushes all objects, not unique ones.

for (const prop in this.totals) {
      this.totals[prop].map(prop =>  this.totalProperties.indexOf(prop.property.hash) === -1 ? 
          this.totalProperties.push(prop.property) : null
      );
    }

This is a solution, where I get all the properties objects into a new array. After that, I filter the array setting only the unique objects by hash. Is there a better way to filter them when pushing into this.totalProperties array? Therefore, I would not have to push them all, and then filter by hash. I want to filter while pushing.

 for (const prop in this.totals) {
      this.totals[prop].map(prop =>
this.totalProperties.push(prop.property));
    }
    
const generalProps = [...new Map(this.totalProperties.map(item => [item.hash, item])).values()];

grmnth
  • 61
  • 2
  • 8
  • 1
    In questions like this, providing the original array and an expected outcome will help us give you an answer – Win Mar 27 '21 at 12:34
  • This answer may help you: https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – Daantje Mar 27 '21 at 12:52
  • 1
    It was not an answer. They were better details to the post. @Yatin – grmnth Mar 27 '21 at 17:27

2 Answers2

0

A solution might be:

const hashList = [];
for (const prop in this.totals) {
  this.totals[prop].forEach(prop => {
    if (hashList.indexOf(prop.property.hash) === -1) {
      hashList.push(prop.property.hash)       
      this.totalProperties.push(prop.property);
    }
  })
}

You could also use findIndex:

for (const prop in this.totals) {
  this.totals[prop].forEach(prop => {
    if (hashList.findIndex(p => p.hash === prop.property.hash) === -1) {
      this.totalProperties.push(prop.property);
    }
  })
}
Chris'
  • 13,624
  • 1
  • 15
  • 14
  • Thank you! I switched "hashList" to "this.totalProperties" in the findIndex solution and works fine. (this.totalProperties.findIndex(p => p.hash === prop.property.hash) === -1) – grmnth Mar 27 '21 at 19:05
0

Like this?

const allProperties = new Map();
for (const key in this.totals) {
    this.totals[key].forEach(o => {
        allProperties.set(o.property.hash, o.property);
    })
}
this.totalProperties = allProperties.values;
md2perpe
  • 3,372
  • 2
  • 18
  • 22