输入:
[{
email: 'sassa',
password: 'sas'
}]
输出:
[{
email: 'sassa',
password: 'sas' ,
valid: true
}]
我收到了来自node.js的响应,我想在对象中添加'valid'元素,以便以后使用。我该如何实现?当我使用推送时,它不起作用。
答案 0 :(得分:1)
只需分配如下所示的新值即可。
var obj = [{
email: 'sassa',
password: 'sas'
}];
obj[0].valid = true;
console.log(obj);
答案 1 :(得分:1)
答案 2 :(得分:1)
选项1:使用对象传播运算符(最简洁,现代和推荐)
const before = {
email: 'sassa',
password: 'sas'
}
const after = {...before, valid: true}
console.log(after) // outputs {email: "sassa", password: "sas", valid: true}
选项2:用户对象。分配(可在更多计算机上使用)
const before = {
email: 'sassa',
password: 'sas'
}
const after = Object.assign(before, {valid: true})
console.log(after)
希望这会有所帮助, 干杯,
答案 3 :(得分:0)
使用对象分配进行制作:
var obj = {
email: 'sassa',
password: 'sas'
};
var result = Object.assign(obj,{valid:true});
console.log(result);
答案 4 :(得分:0)
正如@AbdulBasit已经提到的,push()
仅用于将数据添加到数组而不是字典。
您应该将有效设置为null
或false
,然后将其设置为true
。
var dictionary = {
email: "myemail",
password: "mypassword",
valid: null
};
dictionary.valid = true;
if (dictionary.valid) {
document.write("Valid is set to true.");
}
答案 5 :(得分:0)
https://codepen.io/anon/pen/jeWBZN
var jsonObj = {
obj:
{
email: 'sassa',
password: 'sas'
}
}
var newObj = "valid";
var value = "true";
jsonObj.obj[newObj] = value;
console.log(jsonObj);