我有一个JS函数,应该将键值对添加到JSON对象。
当密钥已经存在时,则应将值附加到现有密钥(嵌套的JSON对象)上。 否则,它应该使用值创建密钥。
目前,有时即使'.hasOwnProperty(key)'方法不存在,它也会返回true。
var myObject= '{}';
function add(key,value){
if(myObject.hasOwnProperty(key)){
var length = Object.keys(myObject[key]).length;
var obj =JSON.parse(myObject);
obj[key] = {};
obj[key][length]= value;
myObject= JSON.stringify(obj);
}
else{
var obj =JSON.parse(myObject);
obj[key] = {};
obj[key]["0"] = value;
myObject= JSON.stringify(obj);
}
}
JSON对象的样子
myObject = {
"50": {
"0": "value1",
"1": "value2",
},
"51": {
"0": "value3",
"1": "value4",
}
};
答案 0 :(得分:0)
尝试一下:
const addEntry = (myObject, key, value) => ({ ...myObject, [key]: value });
console.log(addEntry({}, "hi", 5)); // { "hi": 5 }
console.log(addEntry({ key: 5 }, "hi", 5)); // { "key": 5, "hi": 5 }
console.log(addEntry({ key: 5 }, "key", 2)); // { "key": 2 }
答案 1 :(得分:0)
使用“ in”运算符检查对象中是否存在键
var car = {make: 'Honda', model: 'Accord', year: 1998};
console.log(car);
console.log('make in car: ', 'make' in car);
// expected output: true
delete car.make;
console.log('removed make');
console.log(car);
console.log('add make in again, if not there');
if ('make' in car === false) {
car.make = 'Suzuki';
}
console.log('car.make : ', car.make);
// expected output: "Suzuki"
答案 2 :(得分:0)
尝试以下代码
var myObject= {};
function add(key,value){
myObject.hasOwnProperty(key) ? myObject[key][Object.keys(myObject[key]).length]= value : myObject[key] = {"0": value};
}
add(50, "Hello")
add(50, "World")
add(51, "World")
console.log(myObject)