David Garcia
David Garcia

Reputation: 2696

Javascript: Map iterate object keys and values

Trying to get both key and value using the following script

jsonData = {"jurisdiction":"SCPB - LON","firstName":"David Dynamic"}

var keys   = Object.keys(jsonData).map(function(keys, values) {
    logInfo(jsonData[keys], jsonData[values]);              
});

returns just the values:

2022-08-30 18:29:49 David Dynamic undefined
2022-08-30 18:29:49 SCPB - LON undefined

How can I get both? the js engine is spiderMonkey 1.8

Upvotes: 0

Views: 91

Answers (2)

yurish
yurish

Reputation: 919

Object.keys(jsonData).forEach(function(key) {
    logInfo(key, jsonData[key]);              
});

Object.keys documentation

Or as suggested by Kondrak Linkowski:

Object.entries(jsonData).forEach(([key, value]) => logInfo(key, value))

Upvotes: 3

A_A
A_A

Reputation: 1932

You likely want to use Object.entries to get the keys and values of the object.

If you want to do it with Object.keys, as in your example, you can modify it like this: (logging the key, and the value at this key)

const jsonData = {
 foo: 'bar',
 fizz: 'fuzz',
}
const logInfo = console.log

var keys = Object.keys(jsonData).map(function(key) {
    logInfo(key, jsonData[key]);              
});

Upvotes: 2

Related Questions