Nalini Wanjale
Nalini Wanjale

Reputation: 1757

change data in JSONObject in jsonArray

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??

Upvotes: 0

Views: 62

Answers (1)

konole
konole

Reputation: 766

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;
}, []);

Upvotes: 1

Related Questions