如何获取对象数组中对象的所有属性值的数组?

Met*_*ode 4 javascript arrays javascript-objects ecmascript-6

我想获得每个对象的值的数组.

我有这个:

const numDataPoints = [
    {
      x0: {x: 807, y: 625},
      x1: {x: 15, y: 20},
      x2: {x: 5, y: 20}
    },
    {
      x0: {x: 11, y: 6},
      x1: {x: 16, y: 21},
      x2: {x: 7, y: 22}
    }
  ];
Run Code Online (Sandbox Code Playgroud)

我要这个:

[
  [807, 625],
  [15, 20],
  [5, 20],
  [11, 6],
  [16, 21],
  [7, 22]
]
Run Code Online (Sandbox Code Playgroud)

我试过这个:

numDataPoints.map((array) => array.map(axis => [axis.x, axis.y]));
Run Code Online (Sandbox Code Playgroud)

但它抛出了这个错误:

未捕获TypeError:array.map不是一个功能

Nen*_*car 7

您可以使用map方法Object.values和扩展语法....

const data =  [{ x0: {x: 807, y: 625}, x1: {x: 15, y: 20}, x2: {x: 5, y: 20} }, { x0: {x: 11, y: 6}, x1: {x: 16, y: 21}, x2: {x:7, y: 22} }];

const result = [].concat(...data.map(Object.values)).map(Object.values)
console.log(result)
Run Code Online (Sandbox Code Playgroud)


mic*_*ckl 5

您可以使用Array.map将每个对象转换为双元素数组的数组,然后缩小以展平结果:

const numDataPoints =  [{ x0: {x: 807, y: 625}, x1: {x: 15, y: 20},
            x2: {x: 5, y: 20} }, { x0: {x: 11, y: 6}, x1: {x: 16, y: 21}, x2: {x:7, y: 22} }];

let result = numDataPoints.map(
    item => Object.values(item).map(({x, y})=> [x, y]))
              .reduce((arr, current) => [...arr, ...current], []);

  console.log(result);
Run Code Online (Sandbox Code Playgroud)