JS 数值操作 一维数组转二维数组快捷操作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS 数值操作 一维数组转二维数组快捷操作相关的知识,希望对你有一定的参考价值。

参考技术A //一维数组变二维数组

let list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27];  //示例

function TwoArray(list,index)

if(!Array.isArray(list) || isNaN(index)) return false;

let list_json = JSON.parse(JSON.stringify(list));

let data = [];

for(let i = 0;i<list_json.length;i++)

data.push( list_json.splice(0,list_json.length>index?index:list_json.length))

i = list_json.length>index?0:i



if(list_json.length>0)data.push(list_json);

return data;



console.log(TwoArray(list,8))

js 实现数组对象转成一维二维数组

一维数组实现

const obj = [
    {
        name: '张飒',
        age: 13,
        phone: 123
    },
    {
        name: '凯苏',
        age: 15,
        phone: 963
    },
    {
        name: 'Jk',
        age: 16,
        phone: 852
    },
    {
        name: '库洛',
        age: 17,
        phone: 741
    }
]
//  Object.entries 依据对象的键值对形成数组
// join(',') 数组转字符串
// split(",") 将字符串进行分割
const newArray = []
const arr = obj.map(item => {
    const resultString = Object.entries(item).join(',').split(",")
    /**
    resultString 输出结果
    ["name","张飒","age","13","phone","123"]
	["name","凯苏","age","15","phone","963"]
	["name","Jk","age","16","phone","852"]
	["name","库洛","age","17","phone","741"]
    */
    
    resultString.forEach(key => {
        newArray.push(key)
    })
})
console.log(newArray)  
//  ["name","张飒","age","13","phone","123","name","凯苏","age","15","phone","963","name","Jk","age","16","phone","852","name","库洛","age","17","phone","741"]

二维数组实现

const obj = [
    {
        name: '张飒',
        age: 13,
        phone: 123
    },
    {
        name: '凯苏',
        age: 15,
        phone: 963
    },
    {
        name: 'Jk',
        age: 16,
        phone: 852
    },
    {
        name: '库洛',
        age: 17,
        phone: 741
    }
]

const arr = obj.map(item => {
    const resultString = Object.entries(item).join(',').split(",")
    return resultString.map(item => item)
})
console.log(arr)
//  [["name","张飒","age","13","phone","123"],["name","凯苏","age","15","phone","963"],["name","Jk","age","16","phone","852"],["name","库洛","age","17","phone","741"]]

以上是关于JS 数值操作 一维数组转二维数组快捷操作的主要内容,如果未能解决你的问题,请参考以下文章

js中 把二维数组转成一维数组

js 一维数组转二维数组

js 一维数组转二维数组

JavaScript 二维数组转一维数组

js 实现数组对象转成一维二维数组

js 实现数组对象转成一维二维数组