如何将数组数组转换为一维数组

时间:2018-11-16 03:55:06

标签: javascript

[
  [{
    "_id": "5be9a07c7791b4083fbda644",
    "resource": "one",
    "code": 1,
    "__v": 0
  }],
  [{
    "_id": "5be9a0877791b4083fbda645",
    "resource": "two",
    "code": 2,
    "__v": 0
  }]
]

我在数组中有一个数组,并且我试图摆脱父数组

6 个答案:

答案 0 :(得分:1)

您可以使用concat合并数组:

let input = [
  [{
    "_id": "5be9a07c7791b4083fbda644",
    "resource": "one",
    "code": 1,
    "__v": 0
  },
  {
    "_id": "5be9a07c7791b4083fbda6s4",
    "resource": "three",
    "code": 3,
    "__v": 0
  }],
  [{
    "_id": "5be9a0877791b4083fbda645",
    "resource": "two",
    "code": 2,
    "__v": 0
  }]
];

let result = [].concat.apply([], input);

console.log(result);

答案 1 :(得分:1)

尝试.concat()

let input = [
  [{
    "_id": "5be9a07c7791b4083fbda644",
    "resource": "one",
    "code": 1,
    "__v": 0
  }],
  [{
    "_id": "5be9a0877791b4083fbda645",
    "resource": "two",
    "code": 2,
    "__v": 0
  }]
];
var newArr = [];


for (var i = 0; i < input.length; i++) {
  newArr = newArr.concat(input[i]);
}

console.log(newArr);

答案 2 :(得分:0)

let input = [
  [{
    "_id": "5be9a07c7791b4083fbda644",
    "resource": "one",
    "code": 1,
    "__v": 0
  }],
  [{
    "_id": "5be9a0877791b4083fbda645",
    "resource": "two",
    "code": 2,
    "__v": 0
  }]
];

let result = input.map(item => item[0]);

console.log(result);

答案 3 :(得分:0)

使用扩展运算符。 例如,

Select full_national_number, derived_sequence_number, ts
FROM
(
select full_national_number, derived_sequence_number, ts, 
RANK() OVER(Partition by full_national_number ORDER by ts desc) as rnk
from table
)a
WHERE a.rnk = 1;

最好的朋友。

答案 4 :(得分:0)

使用新的flat方法(Chrome 69 +,Firefox 62+和Safari 12 +)。

const arr = [
  [{
    "_id": "5be9a07c7791b4083fbda644",
    "resource": "one",
    "code": 1,
    "__v": 0
  }],
  [{
    "_id": "5be9a0877791b4083fbda645",
    "resource": "two",
    "code": 2,
    "__v": 0
  }]
];

const flattenedArr = arr.flat();
console.log(flattenedArr);

答案 5 :(得分:0)

对于此输入,您还可以使用以下代码

const d = JSON.stringify(input).replace(/\},|\}],/g, '}|').split('|').map(d=> d.replace(/\[|\]/g, '')).map(d=>JSON.parse(d));

Here I use the following step:
1. Conver Object to String,
2. Then replace "}," and "}]," symbol with '}|'
3. Then split by "|", so now I have each object individually as a string.
4. Now I remove other symbols like "[" and "]" from the string.
5. And last I convert each string to Object. And now we have array of objects.