1

I have an object with nested objects. In this object, each objects having two or more sub-objects. I want to get together all sub-objects into an array of data. How to do with JavaScript?

 const category = {
    id: 1,
    title: "a",
    level: 2,
    __parent: {
      id: 2,
      title: "b",
      level: 1,
      __parent: {
        id: 3,
        title: "c",
        level: 0,
      }
    }
  };

The output I want is this:

   [{
    id: 1,
        title: "a",
        level: 2,
    __parent: null
    },
    {
     id: 2,
          title: "b",
          level: 1,
    __parent: null
    
    },
    {
      id: 3,
            title: "c",
            level: 0,
    __parent:null
    
    }]
1
  • 1
    Hi. Code that you've worked on to solve the problem should include a minimal reproducible example, and be included in your question. Commented Sep 19, 2021 at 12:11

5 Answers 5

1

Case 1: Using Recursion

You can make recursive function like this:

const category = {
  id: 1,
  title: "a",
  level: 2,
  __parent: {
    id: 2,
    title: "b",
    level: 1,
    __parent: {
      id: 3,
      title: "c",
      level: 0,
    }
  }
};

const result = [];

function recursiveOuput(data){
  let tempObj = {};
  Object.keys(data).map((key, index) => {
     if(typeof data[key] !== 'object'){
      tempObj[key] = data[key];
      if(!Object.keys(data).includes('__parent') && (index === Object.keys(data).length -1)){
        tempObj['__parent'] = null;
        result.push(tempObj);
      }
     }else{
      tempObj['__parent'] = null;
      result.push(tempObj);
      recursiveOuput(data[key]);
     } 
  })
  return result;
};

console.log(recursiveOuput(category));


Case 2: Using While loop

const category = {
  id: 1,
  title: "a",
  level: 2,
  __parent: {
    id: 2,
    title: "b",
    level: 1,
    __parent: {
      id: 3,
      title: "c",
      level: 0,
    }
  }
};

const result = [];

let parent = category;

while (parent) {
  result.push({
    id: parent.id,
    level: parent.level,
    title: parent.title,
    __parent: null
  })
  parent = parent.__parent
};

console.log(result);

Sign up to request clarification or add additional context in comments.

5 Comments

thank you for you'r answer can i know if i want the recursiveOuput function in (case 1) return this array of result how should be?
how could be if recursiveOuput function in (case 1) retun the array of data instead of pushing to another value in this case is (result) p.s : i want recursiveOuput function return the array
i want recursiveOuput function return the array for example when i use this function and pass the param to this function , this function retun the array
Okay got your question. Will update my answer shortly. @sanaz
1

It Be some like this :

 const myArray = []
const category = ...;

function foo(obj){
    myArray.push({ 
         title:obj.title,
          ....
    })
    if (obj._parent)
        foo(obj._parent)
}
foo(category)

Comments

1

You essentially want to get the list of ancestors.

const ancestors = []
var parent = category
while (parent) {
  ancestors.push({
    id: parent.id,
    level: parent.level,
    __parent: null
  })
  parent = parent.__parent
}

Comments

1

use recursion to extract objects:

 const category = {
    id: 1,
    title: "a",
    level: 2,
    __parent: {
      id: 2,
      title: "b",
      level: 1,
      __parent: {
        id: 3,
        title: "c",
        level: 0,
      }
    }
  };
  
function extract(obj,arr=[]){
    arr.push({...obj,__parent:null})
    if(!obj.__parent){
        return arr
    }
    
    return extract(obj.__parent,arr)    
 }

 let result = extract(category)
 console.log(result)

1 Comment

codesandbox.io/s/frosty-snowflake-50fex?file=/src/… i use your solution but i want to create variable inside the function and return it but its return last object
0

Using Spread/Rest Operator

const category = {
    id: 1,
    title: "a",
    level: 2,
    __parent: {
      id: 2,
      title: "b",
      level: 1,
      __parent: {
        id: 3,
        title: "c",
        level: 0,
      }
    }
  };

const {__parent, ...firstObject} = category;

result = [
    firstObject,
    {...category['__parent'], '__parent': null },
    {...category['__parent']['__parent'], '__parent': null},
];

console.log(result);

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.