【问题标题】:Convert array of Objects to 2d array将对象数组转换为二维数组
【发布时间】:2020-11-10 04:23:01
【问题描述】:

如何转换 ArrayObjects

var tags= [
  {id: 0, name: "tag1", project: "p1", bu: "test"},
  {id: 1, name: "tag2", project: "p1", bu: "test"},
  {id: 2, name: "tag3", project: "p3", bu: "test"}
];

进入这个二维array

[["tag1","p1", "test"],
["tag2","p1", "test"],
["tag3","p3", "test"]]

【问题讨论】:

标签: javascript node.js arrays object


【解决方案1】:

你可以使用map

var tags= [ {id: 0, name: "tag1", project: "p1", bu: "test"}, {id: 1, name: "tag2", project: "p1", bu: "test"}, {id: 2, name: "tag3", project: "p3", bu: "test"} ];
var res=tags.map(o=>[o.name,o.project,o.bu])
console.log(res)

或者您可以使用更通用的方法

var tags= [ {id: 0, name: "tag1", project: "p1", bu: "test"}, {id: 1, name: "tag2", project: "p1", bu: "test"}, {id: 2, name: "tag3", project: "p3", bu: "test"} ];
var res = tags.map(({id,...rest}) => Object.values(rest))
console.log(res)

【讨论】:

  • 我收到一个错误:tags.map 不是一个函数。这个对象数组是从 API 调用中检索到的,并采用我在上面的问题中发布的确切格式。如果它不是一个对象数组,它只是和对象吗?
  • @Omiinahellcat 是的,在这种情况下,它很可能是一个对象而不是数组类型的对象
【解决方案2】:

Array.map 会帮助你。

https://www.geeksforgeeks.org/javascript-array-map-method/

var tags= [
  {id: 0, name: "tag1", project: "p1", bu: "test"},
  {id: 1, name: "tag2", project: "p1", bu: "test"},
  {id: 2, name: "tag3", project: "p3", bu: "test"}
];
          
   var newArr = tags.map(function(val, index){ 
            return [val.name,val.project,val.bu]
   }) 
          
   console.log(newArr) 

【讨论】:

    【解决方案3】:

    如果您想保留所有可以使用的属性

    let twoDArray = tags.map(tag => Object.values(tag))
    
    // [[0, "tag1", "p1", "test"], [1, "tag2", "p1", "test"], [2, "tag3", "p3", "test"]]
    

    【讨论】:

    • ... 甚至tags.map(Object.values)。但无论哪种情况,您都必须确保所有对象的属性顺序相同。
    • 添加运行sn-p。 @khrzstoper
    • .map(({id,...rest}) => Object.values(rest)) 会更接近 OP 的要求
    猜你喜欢
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2015-06-22
    • 2013-02-21
    相关资源
    最近更新 更多