Leonardo Barbiero
Leonardo Barbiero

Reputation: 23

How do I set a JavaScript object's value to null

I have created this JS object from an array.

var rv = {};
$( ".part-name:visible" ).each(function( index ) {
   //rv[$(this).text()] = arrayPartsName[$(this).text()];
   rv[$(this).text()] = arrayPartsName[$(this).text()];
   console.log(rv);
})

4GN: "4GN"
4GNTS: "4GNTS"
042645-00: "042645-00"
503711-03: "503711-03"
573699-05: "573699-05"

I have to use this object with Materialize Autocomplete and I have to edit it. The correct object must be, for example, like this

4GN: null
4GNTS: null
042645-00: null
503711-03: null
573699-05: null

How can do this?

Upvotes: 0

Views: 1039

Answers (1)

Rohan Büchner
Rohan Büchner

Reputation: 5403

Picking up from my comment. You can just set it to null ;) JavaScript is quite a cool language... you can pretty much set any object's properties to anything you want, null, a specific value, or even a function... see some more on the topic

But to focus on your specific question:

Change this line

rv[$(this).text()] = arrayPartsName[$(this).text()];

to

rv[$(this).text()] = null;


Something to be aware of

If you have property or key values in the JSON object with a dash in the name, you have to wrap it in quotes ", otherwise it wont be seen as valid. Although this might not be as evident, or an issue in your example as your keys are being added via the following function $(this).text().

var fruit = {
"pear": null,   // something null
"talk": function() { console.log('WOOHOO!'); }   // function
}

var apple = "app-le"; 

fruit[apple.toString()] = 'with a dash';
fruit["bana-na"] = 'with a dash';

// below is not allowed, the values will be evaluated as 
// properties that dont exist, and then your js will fail
// fruit[pe-ar] = 'with a dash';

fruit.talk();

console.log(fruit);

Upvotes: 1

Related Questions