请教数组操作问题

现有数组

const r = [
    {
        date: "2020-12",
        regNum: "0"
    },
    {
        date: "2021-1",
        regNum: "1"
    },
    {
        date: "2021-2",
        regNum: "10"
    }
]

目标数组

const a = ["2020-12","2021-1","2021-2"]
const b = [0,1,10]
阅读 3k
5 个回答

const a = r.map(o=>o.date)
const b = r.map(o=>Number(o.regNum))

a = r.map(o=>o.date)
b = r.map(o=>o.regNum)

function map(arr) {
    var a = [];
    var b = [];
    for (var i = 0; i < arr.length; ++i) {
        a.push(arr[i].date);
        b.push(+arr[i].regNum);
    }
    return [a, b];
}
console.dir(map(r));

@lie5860 的就好,但是如果想在一个循环里完成,那就 @柯楠 的,或者下面这个 reduce 版本

const [a, b] = r.reduce((acc, { date, regNum }) => {
    acc[0].push(date);
    acc[1].push(parseInt(regNum, 10));
    return acc;
}, [[], []]);

给你一个工具函数参考一下吧:

TS 版本:

type ArrayAttribute<T> = {
  [K in keyof T]: Array<T[K]>
}

function gourpAttributes<T>(list: T[]) {
  const result = {} as ArrayAttribute<T>

  if (list.length === 0) return result

  const [first, ...others] = list
  const keys = Object.keys(first) as Array<keyof T>

  keys.forEach(key => {
    result[key] = [first[key]]
  })

  others.forEach(item => {
    keys.forEach(key => {
      result[key].push(item[key])
    })
  })

  return result
}

JS 版本:

function gourpAttributes(list) {
  const result = {}

  if (list.length === 0) return result

  const [first, ...others] = list
  const keys = Object.keys(first)

  keys.forEach(key => {
    result[key] = [first[key]]
  })

  others.forEach(item => {
    keys.forEach(key => {
      result[key].push(item[key])
    })
  })

  return result
}

用法:

const r = [
  {
    date: '2020-12',
    regNum: '0'
  },
  {
    date: '2021-1',
    regNum: '1'
  },
  {
    date: '2021-2',
    regNum: '10'
  }
]

const result = gourpAttributes(list)

console.log(result.date) // ['2020-12', '2021-1', '2021-2']
console.log(result.regNum) // [0, 1, 10]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题