H5W3
当前位置:H5W3 > 问答 > 正文

js 数组操作的问题

后端给我的数据是这样的:

let obj = [
{
areaName:"华南地区",
cityName:"深圳"
},
{
areaName:"华南地区",
cityName:"广州"
},
{
areaName:"华南地区",
cityName:"海口"
},
{
areaName:"华北地区",
cityName:"黑龙江"
}
];

我该怎么处理才能变成下面这种格式?

{
areaName:"华南地区",
children:[
{
cityName:"深圳"
},
{
cityName:"广州"
},
{
cityName:"海口"
}]
},
{
areaName:"华北地区",
children:[
{
cityName:"黑龙江"
}]
}

回答

var obj = [
    {
        areaName:"华南地区",
        cityName:"深圳"
    },
    {
        areaName:"华南地区",
        cityName:"广州"
    },
    {
        areaName:"华南地区",
        cityName:"海口"
    },
    {
        areaName:"华北地区",
        cityName:"黑龙江"
    }
];
var areaNameArray = [];
obj.forEach(item=>{
    if(!areaNameArray.includes(item.areaName)) {
        areaNameArray.push(item.areaName)
    }
});
var result = areaNameArray.map(areaName=>{
    const children = obj.filter(item=>item.areaName === areaName).map(item=>({areaName:item.areaName}))
    return {
        areaName,
        children
    }
})
function processData(source) {
    const areaNameCash = [];
    const target = [];

    source.map(item => {
      const { areaName, cityName } = item;
      if (areaNameCash.includes(areaName)) {
        const _t = target.filter(item => item.areaName === areaName)[0];
        _t.children.push({ cityName });
      } else {
        areaNameCash.push(areaName);
        target.push({ areaName, children: [{ cityName }] });
      }
    });
    return target;
}

方法里面应该加空数组的处理。

function getTree(arr) {
  return arr.reduce((accumulator, currentValue) => {
    let temp = { areaName: '', children: [] }
    const sameIdx = accumulator.findIndex(x => x.areaName === currentValue.areaName)

    if (sameIdx >= 0) {
      accumulator[sameIdx].children.push({
        cityName: currentValue.cityName
      })
      return accumulator
    } else {
      temp.areaName = currentValue.areaName
      temp.children.push({
        cityName: currentValue.cityName
      })
      accumulator.push(temp)
      return accumulator
    }
  }, [])
}

未经允许不得转载:H5W3 » js 数组操作的问题

赞 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址