5

I have a problem with finding object in nested json! I need to do operations like 'add' to object and 'delete' object in that nested json. Would it be easy to get object by using "JSON.stringify" and in that string find objects ID parameter (every object has its own unique ID). Then from that point find its "wrapper" curly braces ({}) i could get object it self and then delete it or add new object in it.

I had this idea, but have no idea how to select its curly braces... I think it might work, but what do you thing? :)

Here would be the example object! 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));
2
  • Why don't you just find it as an object and then remove it ? Commented Aug 9, 2015 at 19:48
  • I tried to do it with delete, it replaced deleted object with null. i need "nothing" instead. so i thought about stringify... Commented Aug 9, 2015 at 19:58

3 Answers 3

1

You can traverse the nested JSON recursively, to perform the operations you need.

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));

new fiddle: https://jsfiddle.net/ta4pjqew/2

Sign up to request clarification or add additional context in comments.

2 Comments

What if i need to add something to id 44? it might be in 4 level... i tried to use some recursive functions but they didn't placed in actual object, it just showed object where function was in... nothing should be harcoded! This object may have 10 levels.
i can write the recursive function, I wasn't clear on your needs. give me a min...
1

You should be able to just use your objects like you are traversing a big array:

    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));

Comments

0

Take a look at object-scan. Makes it every easy to write clean and maintainable code to modify complex data structures. Here is how one could answer your question.

// 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(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', gone: undefined }, { 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', gone: undefined }, { name: 'fff', id: 13 } ] }, { name: 'eee', id: 12 } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>

Disclaimer: I'm the author of object-scan

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.