Printing object's keys and values

后端 未结 7 1017
暗喜
暗喜 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:44

    If you want to print key and value, even for nested object then you can try this function:

    function printObjectData(obj, n = 0){
        let i = 0;
        var properties = Object.keys(obj);
    
        let tab = "";
        for(i = 0; i < n; i++)
            tab += "\t";
    
        for(i = 0; i < properties.length; i++){                  
            if(typeof(obj[properties[i]]) == "object"){
                console.log(tab + properties[i] + ":");
                printObjectData(obj[properties[i]], n + 1);
            }
            else
                console.log(tab + properties[i] + " : " + obj[properties[i]]);                    
        }
    }
    
    printObjectData(filters);
    

    and the solution will look like this:

    0:
        user : abc 
    1:
        application : xyz 
    

    and if you want to remove 0: and 1: then simply remove

    console.log(tab + properties[i] + ":"); 
    

    after the if statement

    0 讨论(0)
  • 2021-02-01 06:47

    You can access the value using array syntax

    var filters = [{"user":"abc"},{"application":"xyz"}];
    console.log(Object.keys(filters[0])[0]); // prints user
    var term = (Object.keys(filters[0])[0]);
    console.log(filters[0][term]);// prints abc
    
    0 讨论(0)
  • 2021-02-01 06:49
    for (key in filters[0]){
        console.log( key + ": " + filters[0][key]);
    }
    

    Or if you want to print all the values of filters

    for (i in filters){
        console.log(i);
        for (key in filters[i]){
            console.log( key + ": " + filters[i][key]);
        }
    }
    

    On @mplungjan 's comment

    filters.forEach(function(obj, index){
        console.log(index);
        for (var key in obj){
            console.log(key, obj[key]);
        }
    });
    
    0 讨论(0)
  • 2021-02-01 06:52

    for loop for array and for..in iteration for object:

    var filters = [{ "user": "abc"}, {"application": "xyz"}];
    
    for (var i = 0; i < filters.length; i++) { // the plainest of array loops
      var obj = filters[i];
      // for..in object iteration will set the key for each pair
      // and the value is in obj[key]
      for (var key in obj) { 
        console.log(key, obj[key])
      }
    }

    ES6

    [{ "user": "abc"}, {"application": "xyz"}].forEach(
      obj => console.log(Object.entries(obj).flat())
    )

    0 讨论(0)
  • 2021-02-01 06:52

    Lets say that we have a mode object that has some strings in it for example. If we were to do MODE.toString() with just alpha, beta, gamma in the object, what will be returned is [object Object] which is not useful.

    Instead, lets say we wanted to get something nice back like Normal, Sepia, Psychedelic. To do that, we could add a toString: function(){...} to our object that will do just that. One catch to this however is that if we loop through everything in the object, the function it self will also be printed, so we need to check for that. In the example I'll check toString specifically, however, other checks like ... && typeof MODE[key] == "string" could be used instead

    Following is some example code, calling MODE.toString(); will return Normal, Sepia, Psychedelic

    var MODE = {alpha:"Normal", beta:"Sepia", gamma:"Psychedelic",
        toString: function() {
            var r = "";
            for (var key in MODE) {
                if (MODE.hasOwnProperty(key) && key != "toString") {
                    r+= r !== "" ? ", ":"";
                    r+= MODE[key];
                }
            }
            return r;
        }
    };
    
    0 讨论(0)
  • 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
            }
    
    0 讨论(0)
提交回复
热议问题