Printing object's keys and values

后端 未结 7 1012
暗喜
暗喜 2021-02-01 06:04

I want to print a key: value pair from javascript object. I can have different keys in my array so cannot hardcode it to object[0].key1

var filters = [{\"user\"         


        
7条回答
  •  时光说笑
    2021-02-01 06:54

    if you want get all keys in array of object, you can try this one mybe

          let temp = []
            let keys = []
            let result = []
            for (let i = 0; i < data.length; i++) {
              temp = Object.keys(data[i])
              for (let j = 0; j < temp.length; j++) {
                if(!keys.includes(temp[j])){
                  keys.push(temp[j])
                }
    
              }
              temp = []
            }
    
            for (let i = 0; i < data.length; i++) {
                for (let j = 0; j < keys.length; j++) {
                  if(data[i][keys[j]] == undefined){
                    data[i][keys[j]] = ""
                  }
    
                }
    
            }
            return data
    

    or this one if you want take the key from same array 2dimension

                function convertObj(arr){
                let arrResult = []
                for (let i = 1; i < arr.length; i++) {
                let obj={}
                for (let j = 0; j < arr[0].length; j++) {
                    obj[arr[0][j]] = arr[i][j]
    
                }
                arrResult.push(obj)  
    
                }
            return arrResult
            }
    

提交回复
热议问题