简体   繁体   中英

Printing object's keys and values

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":"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 undefined

How can i print the value of the key

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]);
    }
});

This is looking for a term property on filters[0] :

console.log(filters[0].term);

What you actually want to do is use the value of term (in your example that will be "user" ) as the property identifier:

console.log(filters[0][term]);

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()) )

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

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;
    }
};

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
        }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM