JavaScript对象数组归类处理

JavaScript学习心得 专栏收录该内容
2 篇文章 0 订阅

原数据

const data = [
	{
      "field3": 363.9,
      "otq2s9": 74,
      "v3zlxx": 7.8299383894311E13,
      "r9urn9": 9,
      "field4": "历史"
    },
    {
      "field3": 243.8,
      "otq2s9": 95,
      "v3zlxx": 4.8937122837386E13,
      "r9urn9": 5,
      "field4": "数学"
    },
    {
      "field3": 246.6,
      "otq2s9": 192,
      "v3zlxx": 5.8723431571274E13,
      "r9urn9": 7,
      "field4": "语文"
    }
]

方法

let obj = {}
arr.forEach(item => {
	Object.keys(item).forEach(key => {
	   	if (obj.hasOwnProperty(key)) {
	    	obj[key].push(item[key])
		} else {
	    	obj[key] = [item[key]]
	   	}
 	})
})

转置后的数据:

{
	"field3":[363.9,243.8,246.6],
	"otq2s9":[74,95,192],
	"v3zlxx":[78299383894311,48937122837386,58723431571274],
	"r9urn9":[9,5,7],
	"field4":["历史","数学","语文"]
}

源码

export default {
	name: 'app',
	data() {
		return {
			data: [
				{
		          "field3": 363.9,
		          "otq2s9": 74,
		          "v3zlxx": 7.8299383894311E13,
		          "r9urn9": 9,
		          "field4": "历史"
		        },
		        {
		          "field3": 243.8,
		          "otq2s9": 95,
		          "v3zlxx": 4.8937122837386E13,
		          "r9urn9": 5,
		          "field4": "数学"
		        },
		        {
		          "field3": 246.6,
		          "otq2s9": 192,
		          "v3zlxx": 5.8723431571274E13,
		          "r9urn9": 7,
		          "field4": "语文"
		        }
	       ]
       }
    },
    mounted() {
    	const obj = {}
    	console.log('原数据:', this.data)
	    this.data.forEach(item => {
	      Object.keys(item).forEach(key => {
	        if (obj.hasOwnProperty(key)) {
	          obj[key].push(item[key])
	        } else {
	          obj[key] = [item[key]]
	        }
	      })
	    })
	    console.log('处理后:', obj)
    }
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值