Skip to content
Advertisement

React Native : nested JSON object shallow copy (reference) not working

I have a nested JSON objects that looks like {"name", "children": [JSON objects]}. I am trying to add a new child to the object found with a variable path, an array of names.

My code doesn’t work in my React Native app, however it does in the Chrome console, which makes me really confused. Does it have to do with React Native and if so how can i work it out ?

Code uploaded in the Google Console which yields the expected result : j.children[0].children[0] = 'test' :

let j = {"name": "root", children: [{"name": "tag1", children: []}]};
let res = j;
const path = ["tag1"];

for (const name of path) {
   for (const child of res.children) {
      if (child.name == name) {
         res = child;
         break;
      }
   }
}
res.children.push("test");
console.log(j);

The same code, wrapped in a React Native app, tested on an Android emulator (PIXEL_5_API_30), yields {"children": [{"children": [Array], "name": "tag1"}], "name": "root"} which is not the expected behavior ([Array] means empty array).

export default function App() {

const test = () => {
    let j = {"name": "root", children: [{"name": "tag1", children: []}]};
    let res = j;
    const path = ["tag1"];

    for (const name of path) {
      for (const child of res.children) {
        if (child.name == name) {
          res = child;
          break;
        }
      }
    }
    res.children.push("test");
    console.log(j);
}

return (
    <View>
      <Button title="test" onPress={test} />
      <StatusBar style="auto" />
    </View>
  );
}

Answer

Okay after checking, indeed [Array] is not the empty array, and the code works as intended. It seems React Native only display array up to one depth.

Advertisement