2 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以編寫一個(gè)遞歸函數(shù)來在 JSON 對(duì)象的指定索引處插入一個(gè)元素,如下所示:
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: [] })
);

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
假設(shè)file.json是您的 json 字符串
import objects from './file.json'
對(duì)于查詢,你可以想出這樣的東西。
function query(column, value) {
let children = objects.child
return children.find(child => child[column] === value)
}
對(duì)于多個(gè)返回(數(shù)組),請(qǐng)filter改用
function query(column, value) {
let children = objects.child
return children.filter(child => child[column] === value)
}
然后插入數(shù)據(jù)將是:
function insert(column, value, insert) {
if (insert) {
let children = objects.child
let item = children.find(child => child[column] === value)
if (variable.constructor === Array) {
item.child.push(...insert)
} else {
item.child.push(insert)
}
}
}
添加回答
舉報(bào)