0

I have my reference array

const reference = ['prefix', 'suffix', 'student_email']

and my object that looks like this

const obj = {
               'prefix':'John',
               'suffix':'Doe',
               'student_email':'[email protected]',
               'course_code':'PJ4004',
               'professor':'McMillian'
            }

I'd like to remove 'course_code' & 'professor' as its not apart of the reference array. How can I do that?

Expected output:

const obj = {
               'prefix':'John',
               'suffix':'Doe',
               'student_email':'[email protected]',
            }

What I have:

reference.map(v => {
    delete obj[v]; // this will delete what I don't want it to delete
});

How can I only remove those I don't need/ aren't present in the reference array?

1
  • How are you using obj with reactjs? Commented Jul 6, 2016 at 16:03

1 Answer 1

2

You can loop through Object#keys and delete the properties not found in the array:

const reference = ['prefix', 'suffix', 'student_email']
const obj = {
  'prefix':'John',
  'suffix':'Doe',
  'student_email':'[email protected]',
  'course_code':'PJ4004',
  'professor':'McMillian'
}

Object.keys(obj).forEach(i=>{
  if(reference.indexOf(i) === -1) delete obj[i];
});

console.log(obj);

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

7 Comments

Why take an object that allows very fast lookups and convert it to a new structure that results in slower lookups?
...and why answer a closed question?
@squint Sorry, I didin't see the duplicate when I answered. But what i'm doing for convert the object in a "new structure that results in slower lookups"? I'm confused. It's a bad practice to delete properties for an object like this? I'm now confused and interested. I will remove the anwser later, leting you time to answer.
Sorry, I wasn't clear. You're getting all the keys of the object in Array form and iterating all of them. For each key, you're then searching another Array to find the key. So you have a linear traversal of all keys with each of them requiring a separate linear search. An object already gives you the ability to look up keys, so there's no need to perform a linear search on all keys when you can do a direct lookup on only the desired keys in reference. The direct lookup on the object will be faster than a linear search of reference, and will happen less frequently.
Sorry, I had it reversed. I was thinking he was to remove the reference props. This solution is just fine since he wants an intersection instead of a diff.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.