0

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?

5
  • can you post the html code ? Commented Sep 12, 2018 at 13:11
  • If you want your array keys to be null...why don't you just set them to null... rv[$(this).text()] = null;... I might be misunderstanding what you want? Commented Sep 12, 2018 at 13:13
  • @DILEEPTHOMAS the page HTML is generated using PHP. If you want I can post the full js code. Thank you. Commented Sep 12, 2018 at 13:13
  • 1
    @RohanBüchner thank you! Commented Sep 12, 2018 at 13:14
  • @LeonardoBarbiero you're welcome & welcome to StackOverflow. :D Commented Sep 12, 2018 at 13:17

1 Answer 1

1

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);

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

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.