I want to parse this dictionary:
var data = {'Charlie':
{'keys':
{'a': '1',
'b':['1', '2', '3'],
'c': '3'},
},
'Derek':
{'keys':
{'a': '10',
'b': ['9', '8', '7'],
'c': '9'},
}
};
But I want "Charlie" and "Derek" to appear as li names instead of Dummy. Still - I can't since I don't see them in response. They disappear after parsing, leaving:
'keys':
{'a': '1',
'b':['1', '2', '3'],
'c': '3'}
and
'keys':
{'a': '10',
'b': ['9', '8', '7'],
'c': '9'},
The full code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div>
<h3>Div underneath</h3>
<ul id="main-ul">
</ul>
</div>
</body>
<script>
var data = {'Charlie':
{'keys':
{'a': '1',
'b':['1', '2', '3'],
'c': '3'},
},
'Derek':
{'keys':
{'a': '10',
'b': ['9', '8', '7'],
'c': '9'},
}
};
lay_out_tab_structure(data)
function lay_out_tab_structure(response) {
console.log("response in lay_out_tab is", response)
var ul = $('#main-ul');
for (const [key, value] of Object.entries(response)) {
var li = document.createElement('li')
var div = document.createElement('div')
li.append(div);
ul.append(li);
console.log("The key-value pair before passing is", (key, value))
create_row(li, (key, value))
}
};
function create_row(listItem, content) {
console.log("Content in create row is", content)
var mainDiv = $(listItem).children('div');
var name = $('<p >' '<a style="color:inherit;">' "Dummy" '</a>' '</p>');
var titleDiv = $('<div style="position:relative;margin-bottom:1%;"></div>');
titleDiv.append(name);
mainDiv.append(titleDiv);
var RowDiv = $('<div></div>');
$(mainDiv).append(RowDiv);
};
</script>
</html>
Can you help me?
I have already tried this solution and I couldn't get it working: Object.entries() turning keys into arrays
CodePudding user response:
Object.entries()
will, as your code reflects, provide you with a list of 2-element arrays. Your code destructures each of those arrays into your key
and value
variables. All of that is fine.
However, when you want to pass both the key and the value to another function, you'll have to either pass each as a separate parameter, or else collect them back into a 2-element array. The statement
create_row(li, (key, value))
does not do either of those things. The expression (key, value)
is a comma expression and will evaluate only to value
, as you've found out. Thus, you could either change create_row()
to accept a total of 3 parameters and pass key
and value
individually, or else group those two into a new array:
create_row(li, [key, value])
Either way will work. If you go with the array, then inside create_row()
the key will be content[0]
and the value will be content[1]
.