Home > Software engineering >  how to get only one parameter in each object of an array and store them in a separate array using re
how to get only one parameter in each object of an array and store them in a separate array using re

Time:08-16

I have a nested array like below and I need to store "name" parameter in each object in a separate array and display them on the page

nested array:

const dummyArray = [{
    name: "hello2",
    test: [{
        name: "hello3"
    }]
},
{
    name: "hello4",
    test: [{
        name: "hello5",
        test: [{
            name: "hello6"
        }]
    }]
}
];

This is the function I'm trying to get the job done in a recursive way and I'm using useRef in React to store the final values.

const stateRef = React.useRef([]);

function recursive(arr) {
console.log("arr", arr);

if (arr && arr.length > 0) {
  for (let i = 0; i < arr.length; i  ) {
    let obj = arr[i] || null;
    if (obj?.name) {
      stateRef.current.push(obj.name);
    }

    if (obj?.test) {
      recursive(obj.test[i]);
    } else {
      // what would be the logic here
    }
  }
} else {
  return;
}
}

Overall code is in this codesandbox link overall code

Can someone help me to modify the recursive function to get the required values dynamically.

Thank you.

CodePudding user response:

You can use following recursive function as:

CODESANDBOX LINK FOR REACT CODE

const result = [];
function recursive(obj) {
    if (!obj) return;
    if (Array.isArray(obj)) {
        for (let o of obj) {
            if (o.name) result.push(o.name);
            recursive(o.test);
        }
    }
}

const dummyArray = [
    { name: 'hello2', test: [{ name: 'hello3' }] },
    {
        name: 'hello4',
        test: [
            {
                name: 'hello5',
                test: [{ name: 'hello6' }],
            },
        ],
    },
];
recursive(dummyArray);
console.log(result);

CodePudding user response:

Your problem is that you're passing obj.test[i] to your recursive call but really you want to pass obj.test which is the array you're trying to recurse:

recursive(obj.test);

const dummyArray = [{ name: "hello2", test: [{ name: "hello3" }] }, { name: "hello4", test: [{ name: "hello5", test: [{ name: "hello6" }] }] } ];

const stateRef = {current: []}; // example

function recursive(arr) {
  console.log("arr", arr);

  if (arr && arr.length > 0) {
    for (let i = 0; i < arr.length; i  ) {
      let obj = arr[i] || null;
      if (obj?.name) {
        stateRef.current.push(obj.name);
      }
      if (obj?.test) {
        recursive(obj.test);
      }
    }
  } else {
    return;
  }
}

recursive(dummyArray);
console.log(stateRef.current);

For a different approach, I would suggest using .flatMap() with nested recursive calls. The .flatMap() along with the spread syntax ... will merge all nested mapped arrays into one larger resulting array:

const dummyArray = [{ name: "hello2", test: [{ name: "hello3" }] }, { name: "hello4", test: [{ name: "hello5", test: [{ name: "hello6" }] }] } ];

const recursive = (arr = []) => {
  return arr.flatMap(obj => [obj.name, ...recursive(obj.test)]);
}

console.log(recursive(dummyArray));
// React usage for your ref would be:
// stateRef.current = recursive(dummyArray);

The advantage of not modifying your ref from within your recursive function and keeping it pure is that you can call it multiple times without worrying about modifying your ref. It is only once you assign the returned array to your ref does it get updated.

  • Related