从对象的数组获取新的数组[复制]

问题描述 投票:-1回答:5

这个问题已经在这里有一个答案:

我有一个内部有另一个数组的数组。

[
    [
        {
          "userId": 1,
          "title": "title 1",
        },
        {
          "userId": 2,
          "title": "title 2",
        }
    ],
    [
        {
          "userId": 3,
          "title": "title 3",
        }
    ]
]

我试图让只有用户id的新数组。对于如

[
  { "userId": 1 },
  { "userId": 2 },
  { "userId": 3 }
]

array.map(o => o.userId)工程对象的数组,不知道我怎样才能进去阵列。

任何帮助表示赞赏

javascript arrays
5个回答
3
投票

你必须先flat数组:

const data = [
    [
        {
          "userId": 1,
          "title": "title 1",
        },
        {
          "userId": 2,
          "title": "title 2",
        }
    ],
    [
        {
          "userId": 3,
          "title": "title 3",
        }
    ]
]

const result = data.flat().map(({userId}) => ({userId}));
console.log(result);

1
投票

Array.prototype.flat是相当新的;如果你不能使用它,你可以使用reducemap的组合:

const data = [
    [
        {
          "userId": 1,
          "title": "title 1",
        },
        {
          "userId": 2,
          "title": "title 2",
        }
    ],
    [
        {
          "userId": 3,
          "title": "title 3",
        }
    ]
]

const userIds = data.reduce((_, a) => {
	return _.concat(a.map(({ userId }) => ({ userId })))
}, [])

console.log(userIds)

有关map调用中reduce一个好处是,你只遍历数组过一次,而不是链接的。这将有超过比链阵列的方法更大的阵列更好的性能。

所有假设你的数据结构的深度仅为1级!


1
投票

另外一个使用Array.reduce,对于浏览器that don't support Array.flat.

const data = [
  [
    {
      "userId": 1,
      "title": "title 1",
    },
    {
      "userId": 2,
      "title": "title 2",
    }
  ],
  [
    {
      "userId": 3,
      "title": "title 3",
    }
  ]
]

const result = data.reduce((arr, i) => {
  return arr.concat(i.map(({ userId }) => ({ userId })))
}, [])

console.log(result)

1
投票

您可以使用array#concat,然后用解构扁平化阵列和array#map产生的阵列。

const data = [ [ { "userId": 1, "title": "title 1", }, { "userId": 2, "title": "title 2", } ], [ { "userId": 3, "title": "title 3", } ] ],
      result = [].concat(...data).map(({userId}) => ({userId}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

-1
投票

只要得到所有的东西在新数组:)

let arr = [
    [
        {
          "userId": 1,
          "title": "title 1",
        },
        {
          "userId": 2,
          "title": "title 2",
        }
    ],
    [
        {
          "userId": 3,
          "title": "title 3",
        }
    ]
]

let newArr = []
arr.forEach(i => i.forEach(o => newArr.push(o)))
console.log(newArr.map(o => o.userId))
© www.soinside.com 2019 - 2024. All rights reserved.