13

I have this kind of object

I want to get new object with keys that have "exist === true"

const someObj  = {
      super: {
        exist: true
      },
      photo: {
        exist: true
      },
      request: {
        exist: false
      }
}
const newObj = Object.entries(someObj).reduce((newObj, [key, val]) => {
  if (this.key.exist) { // how to check "exist" is true ?
    return { ...newObj, [key]: val }
  }
}, {});

console.log(newObj);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
user1898714
  • 141
  • 1
  • 1
  • 6
  • 1
    `this[key].exist` – Jonas Wilms Apr 20 '18 at 15:38
  • 1
    thank you for answer, I realized I could just use `val.exist` – user1898714 Apr 20 '18 at 15:59
  • Checked the post to resolve the es-lint issue, and got it fixed. Thanks – Raj Rajeshwar Singh Rathore Mar 04 '21 at 07:15
  • @JonasWilms I'm not sure how this question is duplicate with the one referenced. Could you, please, explain to me? – Gerardo Lima Nov 10 '21 at 22:19
  • @GerardoLima indeed that duplicate wasn't really one, seems I've missread the question back then. FWIW the question actually has working code, it's just missing a `return newObj` in the `else` case, so actually should've been closed as "not reproducible as a typo" ... – Jonas Wilms Nov 11 '21 at 10:49
  • @JonasWilms besides that, the question had another error, trying to access `this.key.exist`, instead of `val.exist`. There were silly bugs -- it happens to all -- and @NarendraJadhav found them and fixed. My comments are just to point that the contents here helped me to find solution to a problem, but I almost dismissed, because of the duplicate mark. cheers – Gerardo Lima Nov 11 '21 at 12:20

2 Answers2

25

You can be achieve your required result by following code

DEMO

const someObj = {
  super: {
    exist: true
  },
  photo: {
    exist: true
  },
  request: {
    exist: false
  }
};
const newObj = Object.entries(someObj).reduce((newObj, [key, val]) => {
  if (val.exist) {
    newObj[key] = val;
  }
  return newObj;
}, {})

console.log(newObj);
.as-console-wrapper {  max-height: 100% !important;  top: 0;}
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
0

Another solution would be to filter the entries and then create a new object with Object.fromEntries like so:

const someObj = {
super: {
    exist: true
},
photo: {
    exist: true
},
request: {
    exist: false
}
};

const filtered = Object.fromEntries(Object.entries(someObj).filter(([, value]) => value.exist))

console.log(filtered)
komakino
  • 26
  • 2