如何将JavaScript对象的值设置为null

问题描述 投票:0回答:1

我从一个数组创建了这个JS对象。

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"

我必须使用Materialize Autocomplete这个对象,我必须编辑它。例如,正确的对象必须是这样的

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

怎么办呢?

javascript jquery
1个回答
1
投票

从我的评论中汲取灵感。您可以将其设置为null;)JavaScript是一种非常酷的语言...您可以将任何对象的属性设置为您想要的任何内容,null,特定值,甚至是函数... see some more on the topic

但要关注您的具体问题:

改变这一行

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

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


Something to be aware of

如果您在名称中带有破折号的JSON对象中有property或键值,则必须将其包装在引号"中,否则它将不会被视为有效。虽然这可能不是那么明显,或者在您的示例中存在问题,因为您的密钥是通过以下函数$(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);
© www.soinside.com 2019 - 2024. All rights reserved.