2021年1月28日星期四

How to transform this specific js array into js object?

I have one javascript array got from back end api, for convenience, need to be sort into the form of below, described as final target.

But I don't know how to start. Anyone can help?

The original src array is like below :

var src = [    {      "parent_kind" : "Animal",      "name" : "Cow"    },    {      "name" : "Animal"    },    {      "parent_kind" : "Animal",      "name" : "Dog"    },    {      "parent_kind" : "Animal",      "name" : "Horse"    },    {      "name" : "Vehicle"    },    {      "parent_kind" : "Vehicle",      "name" : "Bus"    },    {      "parent_kind" : "Bus",      "name" : "Shuttle"    },  ]  

The final target is :

{    "Vehicle" : {      "Bus" : {        "Shuttle" : {}      }    },    "Animal" : {      "Cow" : {},      "Dog" : {},      "Horse" : {}    }  }  

I can got each element of the original array by

for (let ele of src) {    console.log(ele)  }  

enter image description here

https://stackoverflow.com/questions/65948247/how-to-transform-this-specific-js-array-into-js-object January 29, 2021 at 11:06AM

没有评论:

发表评论