0

As we all know, we can use if else to add an attribute to object like this:

if(key){
  obj[key] = value
}

but I have a lot of keys.

I know I can get this done like this:

keyValues.forEach(({key,value})=>{
if(key){
  obj[key] = value
}
}

but i want to know can i do this in another way like:

obj={
 [this.key1?'key1':undefined]:this.key1,
 [this.key2?'key2':undefined]:this.key2,
}

in this way,the object will get an attribute which key is undefined... how can i do to remove undefined attribute and keep the code style in the second way.

0

3 Answers 3

1

Using keyValues from post:

let obj = {};
let keyValues = [
    {
        "key": "a",
        "value": 1
    },
    {
        "key": "b",
        "value": 2
    },
    {
        "key": "c",
        "value": 3
    },
    {
        "value": "nothing"
    }
];

/**
* @returns only 'a', 'b' and 'c' keys
*/
Object.assign(obj, keyValues.reduce((acc, { key, value }) => ({
    ...acc,
    ...key ? { [key]: value } : {},
}), {}))

or u can use the _reject from lodash https://lodash.com/docs/4.17.15#reject

Object.assign(obj, _.reject(keyValues, v => !v.key).reduce((acc, { key, value }) => ({
    ...acc,
    [key]: value,
}), {}))

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

Comments

0

After mounting your obj, you can use the delete operator from js

delete obj.undefined

this will keep your obj clean, if you insist on instantiating it that way;

Comments

0

You could wrap it in a helper function that remove falsy keys

const omit = (obj) =>
  Object.fromEntries(
    Object.entries(obj).filter(
      ([key]) => !["undefined", "null", "false", ""].includes(key)
    )
  );

const obj = omit({
  [undefined]: 1,
  [false]: 2,
  [null]: 3,
  a: "b",
});

console.log(obj);

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.