0

I have been stuck on this awhile. Found a lot of example on how to remove based on key, but not on value.

I am trying to remove all keys that have value false.

Any help would be appreciated, It seems Object.keys only accesses keys, val seems to have no effect.

const names = {
  1: false,
  2: true,
  3: true,
  5: false
}

const newNames = Object.keys(names).reduce((object, key, val) => {
  console.info('propName', key);
  if (object[val] == true) {
    object[key] = names[key];
  }
  return object;
}, {});
console.info('test', newNames);
// expected output I want should be  {2:true, 3:true}

Any help would be appreciated.

4 Answers 4

1

Try checking names[key] is true

const names = {
  1: false,
  2: true,
  3: true,
  5: false
}

const newNames = Object.keys(names).reduce((object, key, val) => {
  if (names[key]) {
    object[key] = names[key];
  }
  return object;
}, {});

console.info('test', newNames);

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

Comments

1

well if you want to modify the object itself, you event don't need to declare a new object. use delete

const names = {
  1: false,
  2: true,
  3: true,
  5: false
}
for (let k in names){if(!names[k]){delete names[k]}}
console.log(names)

Comments

0
const names = {
  1: false,
  2: true,
  3: true,
  5: false
}

for(let name of Object.keys(names)) {
    if(names[name] === false) {
        delete names[name];
    }
}

1 Comment

Please don't post only code as an answer, but also include an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality and are more likely to attract upvotes.
0
Object.keys(names).map(val => {  if(names[val] == false) { delete names[val] } });

1 Comment

Please don't post only code as an answer, but also include an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality and are more likely to attract upvotes.

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.