Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

How to break a dynamically created json into multiple parts based on key in react/javascript

I have dynamic json example below:

{
  "fields": {
    "a": {
      "#type": "textfield"
    },
    "d": {
      "#type": "label"
    }, 
    "f": {
      "#type": "email"
    },
    "g": {
      "#type": "phone"
    },
    "j": {
      "#type": "label"
    }
  }
}

based on the key label I need to split it into multiple json parts. Example:

{
  "fields": {
    "a": {
      "#type": "textfield"
    }
}
{
  "fields": {
    "d": {
      "#type": "label"
    }
}
{
  "fields": { 
    "f": {
      "#type": "email"
    },
    "g": {
      "#type": "phone"
    },
}
{
  "fields": {
    "j": {
      "#type": "label"
    },
}

Note: the json structure can be increase or decrease bcaz its a dynamic data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do the following using reduce,

obj = {
  "fields": {
    "a": {
      "#type": "textfield"
    },
    "d": {
      "#type": "label"
    }, 
    "f": {
      "#type": "email"
    },
    "g": {
      "#type": "phone"
    },
    "j": {
      "#type": "label"
    }
  }
}

ret = Object.keys(obj.fields).reduce((prev, curr) => {
  breakPointFound = false;
  Object.values(obj.fields[curr]).forEach(item => {
    if(item === 'label') {
      breakPointFound = true;
    }
  })
  if(breakPointFound) {
    prev.push({ fields: {
      [curr]: obj.fields[curr],
    }});
    prev.push({fields: {}});
  } else {
    if(prev.length) {
        prev[prev.length - 1].fields[curr] = obj.fields[curr];  
    }
    else {
      prev.push({fields: { [curr]: obj.fields[curr]}});
    }
  }
  return prev;
}, []);

if(Object.keys(ret[ret.length - 1].fields).length === 0) {
  ret.splice(ret.length -1);
}
console.log(ret);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...