javascript - 无法将对象插入到 json 对象数组中

标签 javascript jquery json

对不起,这个简单的问题 - 但我似乎错过了一些明显的东西。任何指针都会有很大的帮助。

我有一个像

这样的 JSON
var  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 不是函数

fiddle

最佳答案

对象上没有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/

相关文章:

javascript - 正则表达式javascript如何检查aa_bb

javascript - 从 ajax 调用获取数据并填充模板

jquery datepicker range - 自动显示第二天

javascript - Grails 使用资源控制 javascript 位置

python - 使用Python解析JSON并返回所有匹配的字段

javascript - Json参数转换继承Web api 2

javascript - 流量: Simpler way to annotate `type | typeof undefined` ?

javascript - Node.js:如何跟踪我的 API 使用情况?

javascript - onclick 函数在 jquery 中不起作用

python - NumPy 数组不是 JSON 可序列化的