Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65948247/how-to-transform-this-specific-js-array-into-js-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can do that with a simple Array.reduce() method

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' } 
  ] 

let res = src.reduce((a,{parent_kind,name},i)=>
  {
  if(!!parent_kind) 
    {
    let np = a.p.find(x=>x.pN===parent_kind)
    if(!np)
      {
      a.r[parent_kind] = {}
      np = {pN:parent_kind, e:a.r[parent_kind]} 
      a.p.push( np )
      }
    let z = np.e[name] = {}
    a.p.push( {pN:name, e:z} )
    }
  return (i===a.len)? a.r : a    
  }
  ,{len:src.length-1,r:{},p:[]})

console.log( res )
.as-console-wrapper { max-height: 100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...