0

I have jsonArray as follows

JSONArray childern as

 [{"id":2,"label":"w","remoId":135},
  {"id":3,"childern":null,"loc":146,"label":"Loc-w"},
  {"id":4,"childern":null,"loc":147,"label":"Loc-newjk"}
 ]

i want to change childern key of JSONObject having id=3 to childernArray where

  childernArray is  [{"id":6,"label":"w"},{"id":7,"label":"w"}]

I want following output

[{"id":2,"label":"w","remoId":135},
 {"id":3,
        "childern":[{"id":6,"label":"w"},
                    {"id":7,"label":"w"}],
         "loc":146,"label":"Loc-w"},
 {"id":4,"childern":null,"loc":147,"label":"Loc-newjk"}]

How can i do this??

1 Answer 1

1

Use Array.prototype.reduce() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

jsonArray.reduce(function(previousValue, currentValue, index, array) {
  if(currentValue.id == 3) {
    currentValue.children = childrenArray;
  }
  previousValue.push(currentValue);
  return previousValue;
}, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.