6

私のアプリケーションでは、次のようなサーバーからのJSON応答に基づいてJavaScriptオブジェクトを作成します。

{
  name: "root",
  id: 1,
  children: [
    {
      name: "child one",
      id: 11,
      children: [
       {name: "grand child 1", id: 111, children: []},
       {name: "grand child 2", id: 112, children: []}
      ]
   },
   {
     name: "child two",
     id: 12,
     children: []
   }
  ]
}

次のような新しいノードを作成します。

 {name: "grandchild three", id: 113, children:[]}

これを念頭に置いて、この新しい孫をID11の親に追加するにはどうすればよいですか。ノードへの静的パスがわからないことに注意してください。id == 11そのため、ノードを知っているだけでそのノードを取得するにはどうすればよいのでしょうかid

編集:実際の場合、IDはオブジェクトへのパスをエンコードしないことに注意してください。扱っているデータ構造のデモンストレーションのために、この簡単な例を作成しました。しかし、実際のアプリケーションでは、そのIDを使用してオブジェクトへのパスを取得できません。

4

5 に答える 5

9

このフィドルを参照してください:http://jsfiddle.net/2Dvws/

IDでオブジェクトを検索します。そして、新しい子をプッシュします。Javascript内のすべてのオブジェクトは参照であるため、varとして返すことができます。

var ob = {
    name: "root",
    id: 1,
    children: [
        {
        name: "child one",
        id: 11,
        children: [
            {
            name: "grand child 1",
            id: 111,
            children: []},
        {
            name: "grand child 2",
            id: 112,
            children: []}
        ]},
    {
        name: "child two",
        id: 12,
        children: []}
    ]
};

見つかった要素を返す関数。すべての子要素を調べます。

function findObjectById(root, id) {
    if (root.children) {
        for (var k in root.children) {
            if (root.children[k].id == id) {
                return root.children[k];
            }
            else if (root.children.length) {
                return findObjectById(root.children[k], id);
            }
        }
    }
};

var bla = findObjectById(ob, 111);

console.log(bla);
bla.children.push({
        name: "child x",
        id: 1111,
        children: []
});
console.log(ob);

出力では、ID111の子にはID1111の子が1つあります</p>

于 2012-10-15T16:41:33.793 に答える
2

idは、親IDと子配列のインデックス(1から9)で構成されていると思いますか?次に、そのように行くことができます:

var rootobj = {…};
var newnode = {name: "grandchild three", id: 113, children:[]};

var id = ""+newnode.id;
var cur = [rootobj];
for (var i=0; i<id.length-i; i++)
    cur = cur[id.charAt(i)-1].children;
cur[id.charAt(i)-1] = newnode;
于 2012-10-15T16:22:13.340 に答える
2

Nielsの答えは良いスタートですが、ツリーを完全にトラバースしません(たとえば、探しているノードがルートの2番目の子の子である場合は壊れます)。また、ルートが探しているIDである場合、それは壊れます。これが私の改良点です:

  function findObjectByID(root, id) {
    if (root.name == id){
      return root;
    }
    if (root.children) {
      for (var k in root.children) {
        if (root.children[k].name == id) {
          return root.children[k];
        }
        else if (root.children[k].children) {
          result = findObjectByID(root.children[k], id);
          if (result) {
            return result;
          }
        }
      }
    }
  };
于 2016-06-17T19:11:35.543 に答える
0

これはどう。

for(var a = 0; a < object.length; a++) {
    for(var b = 0; b < obj.children.length; b++) {
        if(object[a].children[b].id == 11) {
           object[a].children[b].children.push({
                name: "grandchild three", 
                id: 113, 
                children: []
            });
        }
    }
}
于 2012-10-15T16:13:13.690 に答える
0

これがobject-scanを使用した解決策です。ライブラリを使用すると、これがもう少し読みやすく、保守しやすくなります。

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

const insert = (haystack, parentId, node) => objectScan(['**.id'], {
  abort: true,
  rtn: 'bool',
  filterFn: ({ value, parent }) => {
    if (value === parentId) {
      parent.children.push(node);
      return true;
    }
    return false;
  }
})(haystack);

const obj = { name: 'root', id: 1, children: [ { name: 'child one', id: 11, children: [ { name: 'grand child 1', id: 111, children: [] }, { name: 'grand child 2', id: 112, children: [] } ] }, { name: 'child two', id: 12, children: [] } ] };

console.log(insert(obj, 11, { name: "grandchild three", id: 113, children: [] })); // true iff inserted
// => true

console.log(obj);
// => { name: 'root', id: 1, children: [ { name: 'child one', id: 11, children: [ { name: 'grand child 1', id: 111, children: [] }, { name: 'grand child 2', id: 112, children: [] }, { name: 'grandchild three', id: 113, children: [] } ] }, { name: 'child two', id: 12, children: [] } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

免責事項:私はオブジェクトスキャンの作成者です

于 2020-11-18T06:13:24.487 に答える