0

Looking for a shorthand method to assign properties to an object ONLY when the assigning variable is defined.

Current Code:

let count = {}, one = 1, two = 2, four = 4;
if (one) count.one = one; 
if (two) count.two = two; 
if (three) count.three = three; 
if (four) count.four = four; 

Result:
count = { one: 1, two: 2, four: 4 }

Normally, I would try this:

let count = { one, two, three, four }

However, it complains when three is undefined...

Is there a better method to shorthand assign only when defined?

What I cannot have:

count = { one: 1, two: 2, three: undefined, four: 4 }

Steve S
  • 69
  • 7
  • What's wrong with `undefined`? Any code that uses the object should work the same with not defined properties and `undefined`-valued properties. – Bergi May 15 '21 at 04:05
  • @Bergi It's being saved to disk in JSON format and occupies space when assigned a null or undefined. I also wanted to make the JSON uncluttered for easy visual viewing. I was trying to avoid that clutter. But you are somewhat right, the main purpose was to save coding line and make it look neat in the program. I ended up pre-defining all variables to null and just using the let count = {one, two, three, four} in the end, and living with the additional clutter. pre-defining to null allowed me to declare the whole thing without errors. – Steve S May 16 '21 at 02:01
  • No! JSON only knows `null`, it does not represent `undefined`. A property with the value `undefined` will not show up in the `JSON.stringify` result, it's treated as if the property had never been created. Do not initialise the variables with `null`, just declare them (defaulting to `undefined`), and it will work out of the box. – Bergi May 16 '21 at 10:52
  • True enough, but I still have the problem of declaring then stringifying the variable for JSON in one nice elegant line of code without getting the error message of a variable being undefined, unless you know a better way to JSON.stringify({one, two, three, four}) when three is undefined. – Steve S May 16 '21 at 13:26
  • If the variable has the value `undefined`, you won't get an error message - `JSON.stringify({one, two, three, four})` works just fine. If the variable is not *declared*, that's a bug in the code - you need to declare it with `let`/`const`/`var` before using it. – Bergi May 16 '21 at 17:12

4 Answers4

1

it complains when three is undefined...

No, it will only complain when the variable three is not declared, not when it has the value undefined. You can easily fix that:

let one = 1, two = 2, three /* = 3 */, four = 4;

const count = JSON.stringify({one, two, three, four});
console.log(count);

If the variable is not used anywhere, you can just omit it, as it never would have any value. If the variable is used (assigned a value somewhere), you need to declare it anyway in strict mode.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Oh... I stand correct. Good job. Thanks, I believe this is what I needed. I have upvoted your answer as the correct one, but since my reputation is below 15, it will not show. I think however if you upvote my question, I might have the reputation points needed at that point. – Steve S May 17 '21 at 13:40
  • All I need now is to remove that eyesore of {} when none of the variables have a value. Thanks, it worked perfectly. – Steve S May 17 '21 at 13:46
  • For checking whether the object is empty, you can either compare the JSON string against `"{}"`, or use `const obj = {…}; if (Object.values(obj).every(v => v != null)) …` – Bergi May 17 '21 at 14:14
  • Ah.... thank you also for the tutorial on accepting the answer. Done and accepted. One more thing... When scraping the site, I sometimes get an empty element, and would prefer to not create an object property when that happens... ie, count.one = $('#one').val(); Any easy one-liner way to NOT create the property if the value is empty? – Steve S May 17 '21 at 16:27
  • You mean treating the empty string as undefined? You can do that using `count.one = $('#one').val() || undefined;`. Still creates the property though, if you don't want that you won't get around an `if` statement. – Bergi May 17 '21 at 21:00
0

You can create a function to check if the variable is undefined and, if this variable is undefined, you don't add it to the object.

var count = {}, one = 1, two = 2, four = 4;

function addToObject(value){
 if(typeof value === 'undefined') return
 this.count[value] = value;
}

this.addToObject(this.one);
this.addToObject(this.two);
this.addToObject(this.three);
this.addToObject(this.four);
this.addToObject(this.five);

console.log(this.count);
// {1: 1, 2: 2, 4: 4}
0

This only work when the variables are global and can be access by window[name]
You need a string list that contain variable name you trying to get

var target_list = ["one", "two", "three", "four"],
    count = {},
    one = 1, two = 2, four = 4;

for (let target of target_list) {
    if (window[target]) {
        count[target] = window[target];
    } else {
        console.log(`variable [${target}] not found`);
    }
}

console.log(count);

Getting All Variables In Scope

-1

It might be easier if you put the possibly-undefined items onto a particular object. For example, this won't give you a hard time:

const stuff = {
    one: 1, 
    two: 2, 
    four: 4
}

let count = {
    one: stuff["one"],
    two: stuff["two"],
    three: stuff["three"],
    four: stuff["four"]
}

console.log(count)
Aadmaa
  • 829
  • 5
  • 13
  • That made it: { one: 1, two: 2, three: undefined, four: 4 } Which was one of my defined methods that I cannot have... – Steve S May 15 '21 at 02:05
  • Sorry, you want the three to disappear, or to be undefined? – Aadmaa May 15 '21 at 02:06
  • The thing is, once you have it in the object form it is already: const stuff = { one: 1, two: 2, four: 4 } so that's just your starting place. Can you give an example of how you would want to manipulate it from that starting place? – Aadmaa May 15 '21 at 02:07
  • If three is undefined, I need it to not create the property... I am trying to stuff a bunch of variables into a single object, but some of the variables might be undefined. To which, I cannot have them in the object. – Steve S May 15 '21 at 02:08
  • If these are keys on an object, say "A", I think it is trivial because you already have object A and it only has the keys you want. You can list them with Object.keys() . If they are just variables in a script, is it possible that you don't know whether those variables exist? – Aadmaa May 15 '21 at 02:18
  • That is correct, I do not know if the variables exist. The variables are assigned via a web page which may or may not have the element. Thus it would be undefined if the element did not exist. – Steve S May 15 '21 at 02:23
  • Ah ok. Can you define the potential variables as undefined prior to the webpage? Something like this: let x; const y = {} if (x !== undefined) { y["x"] = x } console.log(y) – Aadmaa May 15 '21 at 02:26
  • I've decided to make them null and just clench my teeth at the messy object... maybe I can find a way to 'forEach - delete' the nulls, or something. – Steve S May 15 '21 at 02:44
  • Final Code Ended up Being: ( x => x && Object.keys(x) && ( x = JSON.string(x) ) && sessionStorage.setItem('e', (encode) ? btoa(x) : x) )({ one, two, three, four }); – Steve S May 15 '21 at 02:48