3

Given an array:

var arrOfObj = [{
  name: 'eve',
  col1 : 1,
  col2 : 0,
  col3 : 1
}, {
  name: 'john',
    col1 : 1,
  col2 : 1,
  col3 : 0
}, {
  name: 'jane',
  col1 : 0,
  col2 : 1,
  col3 : 1
}];

I need a field inside the array that has a string of the names of columns col1, col2, col3 if they are 1. Sample outcome is:

var arrOfObj = [{
  name: 'eve',
  col1 : 1,
  col2 : 0,
  col3 : 1,
  account : "col1,col3"
} //etc
}]

I can currently achieve this with

var result = arrOfObj.map(function(o) {
  o.account = ""
  if (o.col1 > 0) {o.account  = o.account + "col1,"} ;
  if (o.col2 > 0) {o.account= o.account + "col2,"} ;
  if (o.col3 > 0) {o.account= o.account + "col3,"} ;
  o.account = o.account.slice(0, -1);
  return o;
})

console.log(result)

but as a novice to JS this feels inefficient. My actual array has a dozen such columns being evaluated.

Edit: finished product with assistance from the accepted answer:

var bool_cols = ["col1","col2","col3"]

data.forEach(x => {
        x.services = Object.keys(x).filter (y => bool_cols.includes(x) && x[y] == 1).join (',');
    })

I like how I can expand the filter criteria indefinitely!

3 Answers 3

3

How about

arrOfObj.forEach ( (x) => {
    x.account = Object.keys(x).filter (y => x[y] == 1).join (',');
})
Sign up to request clarification or add additional context in comments.

3 Comments

Could I do that on only certain parts of the array? Col1, 2, and 3 but not Name?
@DCUFan7 you can add more conditions inside the filter function like filter (y => x[y] == 1 && y.contains("col") )
I love this for making use of filter and join. Looking like includes works for me as well on the second filter. Thank you!
2

I would loop over the keys of the object. And check if key starts with 'col'

var arrOfObj = [{
  name: 'eve',
  col1 : 1,
  col2 : 0,
  col3 : 1
}, {
  name: 'john',
    col1 : 1,
  col2 : 1,
  col3 : 0
}, {
  name: 'jane',
  col1 : 0,
  col2 : 1,
  col3 : 1
}];

const res = arrOfObj.map(x => {
  let acc = [];
  Object.keys(x).forEach(k => {
    if(k.startsWith('col') && x[k] === 1){
      acc.push(k)
    }
  })
  return {...x, account: acc.join(',')}
});

console.log(res)

Comments

1

You can use the var Object.keys(object); to get the keynames of the object and then check the values.

var result = arrOfObj.map(function(o) {
  var keys = Object.keys(o);
  var keyArray = [];
  keys.forEach((key) => {
      if (o[key] > 0) { 
        // Declare the account property, only
        // when it's needed. Otherwise, get it out of the foreach
        keyArray.push(key);
      }
  });
  o['account'] = keyArray.join(',');
});

4 Comments

Updated with the comma.
@AthanasiosKataras that pattern is just bad code, just push into an array and then join by comma at the end ...
Why bother setting the account to an empty string before appending the key. Just set it to the key. Also, working the comma separator into the appended string value just causes confusion and makes it more difficult to manage later when inputs change. Using a join instead, solves all that.
Because += resulted in undefinedcol1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.