繁体   English   中英

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

[英]How do I convert an array of arrays to a 1D array

[
  [{
    "_id": "5be9a07c7791b4083fbda644",
    "resource": "one",
    "code": 1,
    "__v": 0
  }],
  [{
    "_id": "5be9a0877791b4083fbda645",
    "resource": "two",
    "code": 2,
    "__v": 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);

您可以使用Array.prototype.flat()作为let result = input.flat()

flat()方法创建一个新数组,其中所有子数组元素以递归方式连接到指定深度。

或者,您也可以使用concat来合并数组,例如result = [].concat.apply([], input);

 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 = input.flat(); console.log(result); result = [].concat.apply([], input); console.log(result);

试试.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);

使用新的平面方法(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);

使用扩展运算符。 例如,

 const parentArray = [ [{ "_id": "5be9a07c7791b4083fbda644", "resource": "one", "code": 1, "__v": 0 }], [{ "_id": "5be9a0877791b4083fbda645", "resource": "two", "code": 2, "__v": 0 }] ]; const immediateChildArray = [...parentArray]; console.log(immediateChildArray);

所有最好的朋友。

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

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.    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM