Js array processing, object adding properties, array processing into objects

1. This is the

returned by the background.
var b = [{
          channelCategoryName: "",
          channelDetailName: [
            "B",
            "C"
          ]},
          {
            channelCategoryName: "",
            channelDetailName: [
              ""
            ]
         }]

2. This is what I need

var b = [{
            value:"",
            label:"",
            children:[{
                value:"B",
                label:"B"
            },{
                value:"C",
                label:"C"
            }]
        },{
            value:"",
            label:"",
            children:[{
                value:"",
                label:""
            }]
        }] 

turn an into b and ask for advice.

Feb.25,2022

    b.map(item => {
     return {
         value: item.channelCategoryName,
         label: item.channelCategoryName,
         children: item.channelDetailName.map(_item => {
             return {
                 value: _item,
                 label: _item
             }
         })
       }
 })

active use of map is very important


upstairs is right, it is a two-layer loop:

  1. the outermost loop is used to build the final array to be obtained
  2. Inner loop is used to build children

if the landlord is not used to the new syntax of es6 , you can also use the syntax of es5 :

var ret = [];
for (var i in b){
    var 
        item = b[i], 
        tmp={
                value: item.channelCategoryName,
                label: item.channelCategoryName,
                children: []
            };
    
    for (var j in item.channelDetailName) {
        var cItem = item.channelDetailName[j];
        tmp.children.push({
            value: item.channelCategoryName,
            label: item.channelCategoryName,
        });
    }

    ret.push(tmp);
}
console.log(ret)
Menu