-1

I have a JSON structure like below:

"items": {
   "Part1": {
       "src": "xxxx"
   },
   "Part2": {
       "src": "yyyy"
   },
   //...
}

And I want to fetch all the src strings into an array regardless which part it belongs to. So I am trying to navigate through the different parts. How should I achieve this.

Lance Shi
  • 1,127
  • 3
  • 13
  • 28
  • what effort have you made to solving the problem? – Daniel A. White Jun 17 '20 at 02:30
  • @DanielA.White Actually I am currently on a walkaround to this issue. And I am thinking of using findAllChildren but which seems to be applicable to an array instead of this structure. That's why I find this a little bit confusing – Lance Shi Jun 17 '20 at 02:36
  • https://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively – Daniel A. White Jun 17 '20 at 02:37

6 Answers6

1

try this

const items = {
  Part1: {
    src: "xxxx"
  },
  Part2: {
    src: "yyyy"
  }
};

const list = [];
for (const key in items) {
  list.push(items[key].src);
}
Eric Cheng
  • 477
  • 1
  • 9
  • 24
1

You could do this

const items =  {
   "Part1": {
       "src": "xxxx"
   },
   "Part2": {
       "src": "yyyy"
   }
}

const allSrcs = Object.values(items).map(i=> i.src)
console.log(allSrcs)
ABGR
  • 4,631
  • 4
  • 27
  • 49
1

For looping through json/object you can use Object.keys or Object.values. For example in your case,

let data = {
    "items": {
       "Part1": {
           "src": "xxxx"
       },
       "Part2": {
           "src": "yyyy"
       },
       //...
   }
};

let parts = Object.values(data['items']); // retrieve all parts in items
let srcs  = parts.map( p => p.src ); // src array for all parts

console.log(srcs);
HW Siew
  • 973
  • 8
  • 16
1

You can try with this code:

const jsonData = {
    "items": {
       "Part1": {
           "src": "xxxx"
       },
       "Part2": {
           "src": "yyyy"
       },
   }
};

const getAllSrcStringIntoArr = Object.entries(jsonData.items).map(([key,val]) => val.src)

console.log(getAllSrcStringIntoArr)
Deepanshu Gupta
  • 240
  • 1
  • 5
1

To get all src into an array, you can use this solution:

const items =  {
   "Part1": {
       "src": "xxxx"
   },
   "Part2": {
       "src": "yyyy"
   }
};


const results = Object.keys(items).map(item => items[item].src);
console.log(results);
Shivanshu Gupta
  • 324
  • 2
  • 9
0

Here it is:

let vv = Object.values({
  "Part1": {"src": "xxxx"},
  "Part2": {"src": "yyyy"}
}).map(s => s.src);

console.log(vv);