莫回无
您可以编写一个递归函数来在 JSON 对象的指定索引处插入一个元素,如下所示:const yourJSON = `{ "id": "test", "child" : [ { "id": "alpha", "child":[] }, { "id": "beta", "child":[] } ]}`;function insertIntoChildJSON(sourceJSON, childId, childPosition, value) { function insertIntoChild(data, childId, childPosition, value) { if (data.id === childId) { data.child[childPosition] = value; } else { if (data.child.length > 0) { for (let i = 0; i < data.child.length; ++i) { data.child[i] = insertIntoChild( data.child[i], childId, childPosition, value ); } } } return data; } const parsedSource = JSON.parse(sourceJSON); return JSON.stringify( insertIntoChild(parsedSource, childId, childPosition, value) );}console.log( insertIntoChildJSON(yourJSON, 'alpha', 1, { id: 'charlie', child: [] }));