Reputation: 437
I have one json object as below :
{
"firstObject": [
{
"element": ".branding",
"details": "Hello"
},
{
"element": "button.login",
"details": "Hi "
},
{
"element": "#step3",
"details": "How are you "
}
],
"secondObject": [
{
"element": ".branding",
"details": "Hello"
},
{
"element": ".step12",
"details": "Hi "
},
{
"element": "#step2",
"details": "How are you "
}
]
}
And I have below function where above object is passed as parameter (steps):
function getStateSteps (state, steps) {
console.log('TESTTT 1', steps);
let x = Object.keys(steps);
console.log('TESTTT 2', x);
}
Here, In TESTTT 2 log, 'x' is returning index values of strings instead of key of JSON object.But when I am checking for same object in browser console I am getting the correct output. I have attached the screenshot of my browser console. Can someone please point out what is going wrong?
console screenshot
Upvotes: 3
Views: 3589
Reputation: 109
Let me explain why a JSON array would return numeric index values instead of the KEY when using Object.keys.
If your JSON is an array of objects like so...
const thisExample = [ {keys:values}, {keys:values}, {keys:values} ]
then notice that 'thisExample' is just an array[]. So each object{} in that array is at an index within that array, starting at 0 and counting up from there. Technically index values in an array are Keys also. So Object.key is returning that index, or key, value of that array.
Object.keys isn't smart. It gets the index value, which again is also a key. You need to tell it to go deeper and get the keys within the object {}.
Upvotes: 0
Reputation: 365
This can happen when the key was not put inside quotation "" One more example is if you are using for (a in Object.keys(ob)) then a contains the keys of the subobjects of ob so the correct way is for(a in ob)
Upvotes: 0
Reputation: 1352
This works fine:
const data = {
"firstObject": [
{
"element": ".branding",
"details": "Hello"
},
{
"element": "button.login",
"details": "Hi "
},
{
"element": "#step3",
"details": "How are you "
}
],
"secondObject": [
{
"element": ".branding",
"details": "Hello"
},
{
"element": ".step12",
"details": "Hi "
},
{
"element": "#step2",
"details": "How are you "
}
]
};
function getStateSteps (state, steps) {
console.log('TESTTT 1', steps);
let x = Object.keys(steps);
console.log('TESTTT 2', x);
}
getStateSteps(null, data);
Have you stripped this from a broader implementation and perhaps missed a key function?
Whats your dev environment?
Upvotes: 0
Reputation: 2414
Check it again. I have just tried it in my console and it prints exactly as expected.
Try JSON.parse(steps)
before using the json object and see if that helps.
function getStateSteps (state, steps) {
steps = JSON.parse(steps)
console.log('TESTTT 1', steps);
let x = Object.keys(steps);
console.log('TESTTT 2', x);
}
Upvotes: 2