remove object from nested array

前端 未结 4 893
感动是毒
感动是毒 2020-12-03 19:46

I have a familytree looking like this:

{

    \"children\": [{
        \"name\": \"bob\",
        \"children\": [{
            \"name\": \"sam\",
                    


        
4条回答
  •  生来不讨喜
    2020-12-03 19:49

    You can use JSON.stringify(), JSON.parse(), String.prototype.match() with RegExp /\{"name":"sam".*(?=\]\}\]\})/ to match property having property "name" with value "sam" remove remainder of string until ]}]} is portion of string with String.prototype.replace()

    var res = JSON.parse(
      JSON.stringify(data)
      .replace(JSON.stringify(data).match(/\{"name":"sam".*(?=\]\}\]\})/)[0]
      , ""
      , ["children"])
    );
    

    var data = {
    
      "children": [{
        "name": "bob",
        "children": [{
          "name": "sam",
          "children": [{
            "name": "mike",
            "children": [{
              "name": "elias",
              "children": []
            }, {
              "name": "rodriguez",
              "children": []
            }]
          }]
        }]
      }]
    }
    
    var res = JSON.parse(
      JSON.stringify(data)
      .replace(JSON.stringify(data).match(/\{"name":"sam".*(?=\]\}\]\})/)[0]
      , ""
      , ["children"])
    );
    
    console.log(data)
    
    document.querySelector("pre").textContent = JSON.stringify(res, null, 2);

提交回复
热议问题