JS更改数组的数据格式(数组对象互相转换)
时间: 2022-05-14 16:09:18 浏览次数:572
1、对象转数组letobj={"北京市":150,"安徽省":145,"上海市":86,"四川省":46,"陕西省":42,

1、对象转数组

let obj={
    "北京市": 150,
    "安徽省": 145,
    "上海市": 86,
    "四川省": 46,
    "陕西省": 42,
    "湖北省": 41,
    "台湾省": 40,
}
    function convertToArray(objct) {
        return Object.keys(objct).map(key => ({type:key,name:obj[key]}));
    }  
    let arr=convertToArray(obj);   
    console.log(arr)    // [{…}, {…}, {…}, {…}, {…}, {…}, {…}]

2、数组转对象

let arr = [
  {
    "type": "北京市",
    "number": 150
  },
  {
    "type": "安徽省",
    "number": 145
  }
]
let obj = {}
arr.forEach(item=> {
    obj[item.type] = item.number
})
console.log('obj', JSON.stringify(obj, null, 2));    //{北京市: 150, 安徽省: 145}

3、数组格式添加属性

//数组对象添加字段
// arr原数组为[
  //  {fruit: 'apple',price: '25'},
  //  {fruit: 'banana',price: '10'},
  //  {fruit: 'pineapple',price: '15'}
  // ]
  let arr_ = []
  arr.map((item, index) => {
	_arr.push(Object.assign({},item,{flag: false}))
  })
  // arr_返回结果
  // [
  //  {fruit: 'apple',price: '25',flag: false},
  //  {fruit: 'banana',price: '10',flag: false},
  //  {fruit: 'pineapple',price: '15',flag: false}
  // ]

//数组添加属性
let array=["要闻","综合","生活","卫生","教育","军事","国际","社会","经济","体育","文化","科技","时政","农业","法制","国内"]
        let arr=[]
        array.forEach((item,index) => {
          arr.push(Object.assign({ id: index,value: item }));
        });
        console.log(arr);
        //[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
        //0: {id: 0, value: '要闻'}
		//1: {id: 1, value: '综合'}
		//2: {id: 2, value: '生活'}
		//3: {id: 3, value: '卫生'}
		//4: {id: 4, value: '教育'}
        ...

4、数组改为键值对

let a=[{id:1,type:1},{id:2,type:2},{id:3,type:1},{id:4,type:2},{id:5,type:1}]
      const reginObj={}
      a.forEach(item=>{
        reginObj[item.id]=item.type
      })
      let c=reginObj
      console.log(c);     //{1: 1, 2: 2, 3: 1, 4: 2, 5: 1}

5、修改数组内容

	let newObj = [];
      this.cities.map(function(item, index) {
        var sevm = {};
        sevm["id"] = item.id;
        sevm["type"] = 2;
        newObj[index] = sevm;
      });
      this.sourceMap = newObj;

6、取键值对对象的value,及转化为数组

	  let obj = {'11':[1,2],'22':[3,4],'33':[5,6]};
      let arrData = [];
      // this.permissionMap = objData;
      for (let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          arrData.push(obj[key]);
        }
      }
      console.log(arrData);       //[[1,2], [3,4], [5,6]]
      let arr_data = [];
      arrData.map(function(value, index, array) {
        arr_data = arr_data.concat(value);
      });
      console.log(arr_data);       //[1, 2, 3, 4, 5, 6]


Copyright © 2018-2022 七彩网络 All Rights Reserved. 城市服务 鄂ICP备17017594号 XML地图