js数据处理问题

原始数组: [{"year": 2021, months:[1,2,3,4,5,6,7], "total": 123}]

将上面的原始数组怎么处理数据变成如下对象:

{
    "year": 2021,
    "month1": 1,
    "month2": 2, 
    "month3": 3, 
    "month4": 4, 
    "month5": 5,
    "month6": 6,
    "month7": 7,
    "total": 123
}

请大佬们的指点一下, 非常感谢!

阅读 2.6k
5 个回答

参考边城的重新写了一个

var arr = [{"year": 2021, months:[1,2,3,4,5,6,7], "total": 123}];
arr.map(({months,...other})=>{
    var month = Object.fromEntries(months.map(m=>{
        return [`month${m}`,m]
    }));
    return {...month,...other};
})

image.png

第一步,遍历需要转换的数组,
第二步,遍历对象,
第三步,判断值是否是数组,如果是则拼接健和值作为新的键名。

var arr = [{"year": 2021, months:[1,2,3,4,5,6,7], "total": 123}];
arr.map(item=>{
    return Object.entries(item).reduce((acc,[key,val])=>{
        if(Array.isArray(val)){
          val.forEach(v=>{
            acc[key+v]=v;
          })
        } else {
            acc[key]=val;
        }
        return acc;
    },{});
})

image.png

function deal(before){
    var after = {};
    after["year"] = before[0]["year"];
    after["total"] = before[0]["total"];
    for (let i=0; i<before[0]["months"].length; i++){
        after["month" + before[0]["months"][i].toString()] = before[0]["months"][i]
    }
    return after;
}

注:我不太清楚你是否多打了一个"[]",如果是的话,请将所有的before[0]改成before
运行效果:

> var before = [{"year": 2021, months:[1,2,3,4,5,6,7], "total": 123}]
< undefined
> function deal(before){
      var after = {};
      after["year"] = before[0]["year"];
      after["total"] = before[0]["total"];
      for (let i=0; i<before[0]["months"].length; i++){
          after["month" + before[0]["months"][i].toString()] = before[0]["months"][i]
      }return after;
  }
< undefined
> deal(before)
< {year: 2021, total: 123, month1: 1, month2: 2, month3: 3, …}
  month1: 1
  month2: 2
  month3: 3
  month4: 4
  month5: 5
  month6: 6
  month7: 7
  total: 123
  year: 2021
  [[Prototype]]: Object

前面几人的方法肯定可以完成你现在给出源数据到结果数据的转换,但我个人觉得你最好还是解释一下数据要求或者说意义,主要是monthstotal,特别是months与转换后的monthN关系,否则可能因为理解不同而有不同的效果(现在看起来结果是对的,但实际意义却不一样。)
比如你的months数组中各个数字是代表的具体哪个月,还是对应序数月的具体数据,二者的意义是完全不同的。

function transform(arr) {
    var ret = {};
    for (var key in arr[0]) {
        var value = arr[0][key];
        if (value instanceof Array) {
            for (var i = 0; i < value.length; ++i) {
                ret[key.slice(0, -1) + value[i]] = value[i];
            }
        } else {
            ret[key] = value;
        }
    }
    return ret;
}
console.dir(transform([{"year": 2021, months:[1,2,3,4,5,6,7], "total": 123}]));
const cases = [{ "year": 2021, months: [1, 2, 3, 4, 5, 6, 7], "total": 123 }]

function flatMonths(obj) {
    const newOne = {
        ...obj,
        ...Object.fromEntries(obj.months.map(m => [`month${m}`, m]) ?? [])
    };
    delete newOne.months;
    return newOne;
}

console.log(cases.map(flatMonths));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题