0

assume i have an object call userData = {..}

and I want to define an object userDataB with properties a,b,c and d from userData but only of those which defined. I know I can do something like this:

userDataB = {}
if(userData.a){userDataB.a = a};
if(userData.b){userDataB.b = b};
...

but, there is something cleaner? mayber from es5 or es6?

1
  • 2
    Note that your code will produce {} for { a: 0, b: "" }, not sure if that is intended. Commented Mar 28, 2019 at 11:06

4 Answers 4

2

This might help too

const object1 = {
    a: 'somestring',
    b: 42,
    c: false,
    d: undefined
};
let object2 = Object.assign(
    ...Object.entries(object1).map(obj =>
        obj[1] !== undefined ? { [obj[0]]: obj[1] } : {}
    )
);

or this

let object2 = Object.assign(
    ...Object.keys(object1).map(key =>
        object1[key] !== undefined ? { [key]: object1[key] } : {}
    )
);

or this

let object2 = Object.entries(object1).reduce(
    (a, v) => (v[1] !== undefined ? Object.assign(a, { [v[0]]: v[1] }) : a),
    {}
);
Sign up to request clarification or add additional context in comments.

Comments

1

Use JSON methods - they auto-strip undefined properties:

var userData = {
  a: "a",
  b: false,
  c: undefined,
  d: 0
};

var userDataB = JSON.parse(JSON.stringify(userData));

console.log(userDataB);

1 Comment

This will a) also remove any method, Map, Set, Symbolic key etc. b) fail for circular references
0

Just use Object.assign() to clone it into a new object:

var userData = {
  a: 1,
  b: 2,
  d: 3
}
userDataB = Object.assign({}, userData);
console.log(userDataB);

For undefined or null values:

var userData = {
  a: 1,
  b: 2,
  c: null,
  d: 3,
  e: undefined
}
var userDataB = Object.assign({}, userData);
Object.keys(userDataB).forEach((key) => (userDataB[key] == null) && delete userDataB[key])
console.log(userDataB);

3 Comments

This doesn't deal with the "is defined" part of the problem.
@JackBashford now it does
I look for cleaner sultion
0

Depending on your use case, this might work for you:

const newObj = Object.keys(oldObj).reduce((all,propertyName) => {
  if(oldObj[propertyName] != null){ // change this to your criteria
    all[propertyName] = oldObj[propertyName];
  }
  return all;
},{});

Comments

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.