简体   繁体   English

如何将特定的 Json 部分作为独立对象返回?

[英]How to return specific Json part as independent object?

I have Json object as shown below:我有 Json 对象,如下所示:

{
  id : 0,
  cnt: 1,
  someStuff : 'lalala',
  1: {
    id : 1,
    cnt: 2,
    someStuff : 'allgood',
    1: {
      id : 2,
      cnt: 0,
      someStuff: 'nice'
    },
    2: {
      id : 3,
      cnt : 0,
      someStuff: 'nice2'
    }
  }
}

And all I want to do is to return some part of this Json as independent object.我想要做的就是将此 Json 的某些部分作为独立对象返回。 If Im using this function :如果我使用这个功能:

function CurrentNodeReturn(obj, idReturn) {
    if (idReturn == 0) { return obj; }
    for (var i = 1; i < obj.cnt + 1; i++) {
        if (obj[i].id == idReturn) {
            return obj[i];
        } else {
            return CurrentNodeReturn(obj[i], idReturn);
        }
    }
}

I can get the same object I send with Id =0.我可以获得与 Id = 0 发送的相同对象。 Also I can get separated object wit ids 1 and 2. But when I need to get object with id = 3 all i get is "undefined" errors in console log.此外,我可以通过 id 1 和 2 获得分离的对象。但是当我需要获得 id = 3 的对象时,我得到的只是控制台日志中的“未定义”错误。 So how can I improve my function's alghoritm if every time I call CurrentNodeReturn function with parameters (all main object I mentioned, node's id which should be returned to starting call point)?那么,如果每次我用参数(我提到的所有主要对象,应该返回到起始调用点的节点的 id)调用 CurrentNodeReturn 函数时,我该如何改进我的函数的算法?

How can I improve my function's alghoritm if every time I call CurrentNodeReturn function with parameters?如果每次使用参数调用 CurrentNodeReturn 函数时,如何改进函数的算法?

First, you should change your stopping condition to check if the id maches or if the object is undefined.首先,您应该更改停止条件以检查 id 是否匹配或对象是否未定义。

Otherwise, if you do not meet the stop condition, loop over the children and call your function recursively and return the value if it is not undefined .否则,如果您不满足停止条件,则循环遍历子项并递归调用您的函数,如果不是undefined则返回该值。

 const data = { id : 0, cnt: 1, someStuff: 'lalala', 1: { id : 1, cnt: 2, someStuff: 'allgood', 1: { id : 2, cnt: 0, someStuff: 'nice' }, 2: { id : 3, cnt : 0, someStuff: 'nice2' } } }; function getObject(obj, id) { if (!obj || obj.id === id) { return obj; } for (let i = 0; i < obj.cnt; i++) { const child = getObject(obj[i + 1], id); if (child) { return child; } } } console.log(getObject(data, 2)) console.log(getObject(data, 3))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM