对不起,这个简单的问题 - 但我似乎错过了一些明显的东西。任何指针都会有很大的帮助。
我有一个像
这样的 JSONvar whatever = [{
"key1" : { "text" : "text1","group" : "1" },
"key2" : { "text" : "text2","group" : "2" },
"key3" : { "text" : "text3","group" : "3" }
}];
我正在尝试添加另一个对象(最好是在开始时)- 但就是无法让它工作。
var str = '{"text":"text0","group":"0"}';
var obj = JSON.parse(str);
whatever[0].put("key0",obj);
出现以下错误:
未捕获的类型错误:whatever[0].put 不是函数
最佳答案
对象上没有put
函数。使用属性代替它。当您要分配给一个不存在的属性时,它会创建一个新属性并为其分配值。
whatever[0]["key0"] = obj;
与最好在开始相关的,对象属性没有顺序。这是一个错误的说法。如果您想要排序,请尝试从对象数组的 Angular 而不是包含对象的对象数组的 Angular 来思考。
代码示例
const whatever = [{
"key1" : { "text" : "text1","group" : "1" },
"key2" : { "text" : "text2","group" : "2" },
"key3" : { "text" : "text3","group" : "3" }
}];
const str = '{ "text" : "text0", "group" : "0" }';
const obj = JSON.parse(str);
whatever[0]["key0"] = obj;
console.log(whatever);
或者使用Object#assign
const whatever = [{
"key1" : { "text" : "text1","group" : "1" },
"key2" : { "text" : "text2","group" : "2" },
"key3" : { "text" : "text3","group" : "3" }
}];
const str = '{ "text" : "text0", "group" : "0" }';
const obj = JSON.parse(str);
Object.assign(whatever[0], { key0: obj }) // this will also change the object
console.log(whatever);
如果你想要有序的东西,我的建议是使用一个对象数组。
const whatever = [
{ "text" : "text1","group" : "1" },
{ "text" : "text2","group" : "2" },
{ "text" : "text3","group" : "3" }
];
const str = '{ "text" : "text0", "group" : "0" }';
const obj = JSON.parse(str);
// Add to the start
whatever.unshift(obj);
console.log(whatever);
// Add to the end
whatever.push(obj);
console.log(whatever);
关于javascript - 无法将对象插入到 json 对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46360202/