Banani720
Banani720

Reputation: 159

Use Set .forEach() to add items to a specified property of an object

I have a function that returns a set of column numbers and an object defined with some properties

for (let row of excelSheet)
{
  let item = {
    property1: row[column]
    property2: row[column]
    property3: row[column]
  }
}

let's say though that values for property three can be found in more than one column and therefore the set that is returned from the column has more than one value. I tried to set property3: to

row[Number(columnSet.foreach(function(v){return v})]

however, nothing seems to populate in the item and the console logs undefined for that property. Is there a better way to go about this?

Upvotes: 0

Views: 41

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

If there are multiple values, you probably want an array instead. Use .map to iterate over the Set and access the appropriate row, so that the value of item.property3 is an array of values of row[column]s:

property3: [...columnSet].map(column => row[column])

const columnSet = new Set([2, 4]);
const row = [0, 1, 2, 3, 4, 5];
const obj = {
  property3: [...columnSet].map(column => row[column])
};

console.log(obj);

Upvotes: 1

Related Questions