[removed] Setting Nested object value by ID

前端 未结 4 1168
日久生厌
日久生厌 2021-01-21 07:26

I would like to know what is the best way to update the member of the multilevel object collection in JavaScript

Here is the simplified version of my collection:

4条回答
  •  自闭症患者
    2021-01-21 08:02

    You must recursively descend your tree structure searching for the object with the target "id" and replace its text. For example:

    function updateObjectByID(obj, id, text) {
      if (!obj) return;
      if (obj.id === id) {
        obj.text = text;
      } else if ((typeof(obj)==='object') && (obj.constructor===Array)) {
        for (var i=0; i

    However, this solution can be optimized by tree pruning.

提交回复
热议问题