Nabi K.A.Z. Nabi K.A.Z. - 6 months ago 23
Javascript Question

Get `li` elements and push it into object

I have a simple question!

I have this

html
and
js
:

<ul>
<li id="x">foo</li>
<li id="y">bar</li>
</ul>

var data = {
'language': 'fa',
'phrases': {},
};


I want to append all
li
in the
phrases
of
data
for have this output:

{"language":"fa","phrases":{"x":"foo","y":"bar"}}


I try this:

data.phrases.$(this).attr('id') = $(this).html();


And try
push
this:

data.phrases.push( {$(this).attr('id') : $(this).html()} );


And try
extend
this:

data.phrases.extend( {$(this).attr('id') : $(this).html()} );


But does not work!

Completed code:

<ul>
<li id="x">foo</li>
<li id="y">bar</li>
</ul>

<div id="result"></div>

var data = {
'language': 'fa',
'phrases': {},
};

//I want to append all `li` in the `phrases` of `data` for have this output:
//{"language":"fa","phrases":{"x":"foo","y":"bar"}}
$("li").each(function() {
//data.phrases.$(this).attr('id') = $(this).html();
//data.phrases.push( {$(this).attr('id') : $(this).html()} );
//data.phrases.extend( {$(this).attr('id') : $(this).html()} );
});

$("#result").html(JSON.stringify( data ));


See here online code: https://jsfiddle.net/NabiKAZ/fw63jd5k/

Answer

You're quite close! The issue is that the dot operator in JavaScript cannot be used to evaluate a key then access it. You're looking for the [ ] operator, which can be used to evaluate whatever is in the brackets, then use the value as the key. So try this:

data.phrases[$(this).attr('id')] = $(this).html();
Comments