2 回答
TA贡献1865条经验 获得超7个赞
您可以编写一个递归函数来在 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: [] })
);
TA贡献1860条经验 获得超8个赞
假设file.json是您的 json 字符串
import objects from './file.json'
对于查询,你可以想出这样的东西。
function query(column, value) {
let children = objects.child
return children.find(child => child[column] === value)
}
对于多个返回(数组),请filter改用
function query(column, value) {
let children = objects.child
return children.filter(child => child[column] === value)
}
然后插入数据将是:
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)
}
}
}
添加回答
举报