js整理数据格式(动态修改js对象里的key和value)
<script> // 要整理的数据 var array = [ {1: 'name', 2: 'age', 3:'sex', 4:'address'}, {1: 'tom', 2: '12', 3:'sex', 4:'englich'}, {1: 'mark', 2: '13', 3:'sex', 4:'chinese'}, {1: 'jack', 2: '14', 3:'sex', 4:'jpan'} ]; /** * * 想要的效果 * {name: "tom", age: "12", sex: "sex", address: "englich"} * {name: "mark", age: "13", sex: "sex", address: "chinese"} * {name: "jack", age: "14", sex: "sex", address: "jpan"} */ /** * @desc 整理数据格式 * @param {Object} array */ function formatData(array) { var dataList = []; var column = array[0]; console.log('获取key:', column); var newArray = array.slice(1); console.log("删掉第一个元素的新数组:", newArray); for(var a=0; a<newArray.length; a++) { var data = {}; //创建一个空对象,for循环会为空对象动态添加key和value for(var key in column) { data[column[key]] = newArray[a][key]; } dataList.push(data); } console.log("整理数据格式后的数组:", dataList); } //调用整理数据方法 formatData(array); console.log('获取对象里面所有的key:', Object.keys(array[0])); console.log('获取对象里面所有的value:', Object.values(array[0])); </script>