Nicero Nicero - 5 months ago 7
JSON Question

Get the both "ID" and "HREF" attributes and create a JSON object

I have a dinamically generated code as follows which lists some files and let the user delete them by clicking on their links:

<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml
</div>
</div>


Each file has its ID. The list is generated via AJAX when the user uploads the files.

When the user clicks a link, before the file is passed to the "delete.php" call, I would like to have a JSON object that lists all the files like this:

{1 : 1984.xls, 2 : 1984.xml}


I managed to made it using an array

var files = [];

$('#filenames').find('a').each(function() {
files.push($(this).attr('href'));
});


But this simply adds to the array the name of the file which is stored inside
href
.

I don't know how to
find
both
id
and
attr
and create instead of an array a JSON object as said above.

Answer

You have to create an object using {} (and not array []) then affect the key:value to it as files[key] = value when the key is the id of the link and value represented by the href, check the example below.

Hope this helps.

var files = {};

$('#filenames').find('a').each(function() {
  var key = $(this).attr('id');
  var value = $(this).attr('href');

  files[key] = value;
});

console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="filenames">
    <div>
        <a id="1" class="delete" href="#1984.xls">1984.xls
    </div>
    <div>
        <a id="2" class="delete" href="#1984.xml">1984.xml
    </div>
</div>