Traverse all the Nodes of a JSON Object Tree with JavaScript

前端 未结 16 1774
猫巷女王i
猫巷女王i 2020-11-22 06:26

I\'d like to traverse a JSON object tree, but cannot find any library for that. It doesn\'t seem difficult but it feels like reinventing the wheel.

In XML there are

16条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:05

    I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791

    You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/

    Examples of usage: You should always have root object which is the first parameter of each method:

    var rootObj = {
      name: 'rootObject',
      children: [
        {
          'name': 'child1',
           children: [ ... ]
        },
        {
           'name': 'child2',
           children: [ ... ]
        }
      ]
    };
    

    The second parameter is always the name of property that holds nested objects. In above case it would be 'children'.

    The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1} as the third parameter.

    And you can:

    1. findFirst(rootObj, 'children', { id: 1 }) to find first object with id === 1
    2. findAll(rootObj, 'children', { id: 1 }) to find all objects with id === 1
    3. findAndDeleteFirst(rootObj, 'children', { id: 1 }) to delete first matching object
    4. findAndDeleteAll(rootObj, 'children', { id: 1 }) to delete all matching objects

    replacementObj is used as the last parameter in two last methods:

    1. findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change first found object with id === 1 to the { id: 2, name: 'newObj'}
    2. findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'}) to change all objects with id === 1 to the { id: 2, name: 'newObj'}

提交回复
热议问题