在嵌套的json

时间:2015-08-09 19:43:13

标签: javascript json

我在嵌套的json中找到对象有问题!我需要在嵌套的json中执行“添加”对象和“删除”对象等操作。通过使用“JSON.stringify”获取对象是否容易,并在该字符串中查找对象ID参数(每个对象都有自己的唯一ID)。然后从那一点找到它的“包装”花括号({})我可以将它自己对象然后删除它或在其中添加新对象。

我有这个想法,但不知道如何选择它的花括号...我认为它可能有用,但你有什么用? :)

这是示例对象! https://jsfiddle.net/gb8hb8g7/

var aa = [
    {name: "aaa",
     id: 1,
     items: [
         {name: "bbb",
          id: 15,
          items: [
              {name: "ccc",
               id: 44},
              {name: "ddd",
               id: 91}
          ]},
         {name: "eee",
          id: 12}
     ]
    }
];

console.log(JSON.stringify(aa));

3 个答案:

答案 0 :(得分:1)

您可以递归遍历嵌套的JSON,以执行所需的操作。

var aa = [
    {name: "aaa",
     id: 1,
     items: [
         {name: "bbb",
          id: 15,
          items: [
              {name: "ccc",
               id: 44},
              {name: "ddd",
               id: 91}
          ]},
         {name: "eee",
          id: 12}
     ]
    }
];


var fff = {name: "fff", id: 13};
addObj(aa, 91, fff);                       // Add obj to same array as item 91
chgObj(aa, 91, '^', 'name', 'zzz');        // Change 'name' property of item 91
chgObj(aa, 91, '+', 'other', 'test');      // Add property to item 91 
chgObj(aa, 91, '+', 'gone', 'delete me');  // Add property to item 91
chgObj(aa, 91, '-', 'gone');               // Delete property from item 91
dltObj(aa, 44);                            // Delete item 44

function addObj(itemArr, nId, newObj) {
    for (var i = 0; i < itemArr.length; i++) {
        if (itemArr[i].id && itemArr[i].id === nId) {
            itemArr.push(newObj);
        } else {
            if (itemArr[i].items) {
                addObj(itemArr[i].items, nId, newObj);
            }
        }
    }
}

function chgObj(itemArr, nId, operator, prop, val) {
    for (var i = 0; i < itemArr.length; i++) {
        if (itemArr[i].id && itemArr[i].id === nId) {
            switch (operator) {
                case '+':
                    if (!itemArr[i][prop]) {
                        itemArr[i][prop] = val;
                    }
                    break;

                case '-':
                    if (itemArr[i][prop]) {
                        delete itemArr[i][prop];
                    }
                    break;

                case '^':
                    if (itemArr[i][prop]) {
                        itemArr[i][prop] = val;
                    }
                    break;
            }
        } else {
            if (itemArr[i].items) {
                chgObj(itemArr[i].items, nId, operator, prop, val);
            }
        }
    }
}

function dltObj(itemArr, nId) {
    for (var i = 0; i < itemArr.length; i++) {
        if (itemArr[i].id && itemArr[i].id === nId) {
            itemArr.splice(i, 1);
        } else {
            if (itemArr[i].items) {
                dltObj(itemArr[i].items, nId);
            }
        }
    }
}

alert(JSON.stringify(aa));

新小提琴:https://jsfiddle.net/ta4pjqew/2

答案 1 :(得分:1)

你应该能够像使用大型阵列一样使用你的对象:

    var aa = [
    {name: "aaa",
     id: 1,
     items: [
         {name: "bbb",
          id: 15,
          items: [
              {name: "ccc",
               id: 44},
              {name: "ddd",
               id: 91}
          ]},
         {name: "eee",
          id: 12}
     ]
    }
];

aa[0].name = 'abc';
aa[0].newprop = 23;
console.log(aa[0].items[0].items[1]);
delete  aa[0].items[0].items[1];
console.log(aa[0].items[0].items[1]);


console.log(JSON.stringify(aa));

答案 2 :(得分:0)

看看object-scan。轻松编写干净且可维护的代码来修改复杂的数据结构。这是一个可以回答您问题的方法。

const objectScan = require('object-scan');

const tool = (() => {
  const scanner = objectScan(['**.items[*]'], {
    abort: true,
    rtn: 'bool',
    filterFn: ({ value, parent, property, context }) => {
      if (value.id === context.id) {
        context.fn({ value, parent, property });
        return true;
      }
      return false;
    }
  });
  return {
    add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
    del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
    mod: (data, id, prop, v = undefined) => scanner(data, {
      id,
      fn: ({ value }) => {
        if (value !== undefined) {
          value[prop] = v;
        } else {
          delete value[prop];
        }
      }
    })
  };
})();

// -------------------------------

const aa = [{
  name: 'aaa',
  id: 1,
  items: [
    {
      name: 'bbb',
      id: 15,
      items: [
        { name: 'ccc', id: 44 },
        { name: 'ddd', id: 91 }
      ]
    },
    { name: 'eee', id: 12 }
  ]
}];
const fff = { name: 'fff', id: 13 };

const exec = (fn) => {
  console.log('---------------');
  console.log(fn.toString());
  console.log(fn());
  console.log(JSON.stringify(aa));
};

exec(() => tool.add(aa, 91, fff));                  // Add obj to array after item 91
exec(() => tool.mod(aa, 91, 'name', 'zzz'));        // Change 'name' property of item 91
exec(() => tool.mod(aa, 91, 'other', 'test'));      // Add property to item 91
exec(() => tool.mod(aa, 91, 'gone', 'delete me'));  // Add property to item 91
exec(() => tool.mod(aa, 91, 'gone'));               // Delete property from item 91
exec(() => tool.del(aa, 44));                       // Delete item 44

// ---------------
// () => tool.add(aa, 91, fff)
// true
// [{"name":"aaa","id":1,"items":[{"name":"bbb","id":15,"items":[{"name":"ccc","id":44},{"name":"ddd","id":91},{"name":"fff","id":13}]},{"name":"eee","id":12}]}]
// ---------------
// () => tool.mod(aa, 91, 'name', 'zzz')
// true
// [{"name":"aaa","id":1,"items":[{"name":"bbb","id":15,"items":[{"name":"ccc","id":44},{"name":"zzz","id":91},{"name":"fff","id":13}]},{"name":"eee","id":12}]}]
// ---------------
// () => tool.mod(aa, 91, 'other', 'test')
// true
// [{"name":"aaa","id":1,"items":[{"name":"bbb","id":15,"items":[{"name":"ccc","id":44},{"name":"zzz","id":91,"other":"test"},{"name":"fff","id":13}]},{"name":"eee","id":12}]}]
// ---------------
// () => tool.mod(aa, 91, 'gone', 'delete me')
// true
// [{"name":"aaa","id":1,"items":[{"name":"bbb","id":15,"items":[{"name":"ccc","id":44},{"name":"zzz","id":91,"other":"test","gone":"delete me"},{"name":"fff","id":13}]},{"name":"eee","id":12}]}]
// ---------------
// () => tool.mod(aa, 91, 'gone')
// true
// [{"name":"aaa","id":1,"items":[{"name":"bbb","id":15,"items":[{"name":"ccc","id":44},{"name":"zzz","id":91,"other":"test"},{"name":"fff","id":13}]},{"name":"eee","id":12}]}]
// ---------------
// () => tool.del(aa, 44)
// true
// [{"name":"aaa","id":1,"items":[{"name":"bbb","id":15,"items":[{"name":"zzz","id":91,"other":"test"},{"name":"fff","id":13}]},{"name":"eee","id":12}]}]