Reputation: 4377
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.
Upvotes: 1
Views: 371
Reputation: 1
Please try this code
var files = [];
item = {}
$('#filenames').find('a').each(function () {
item[$(this).attr('id')] = $(this).attr('href');
});
files.push(item);
console.log(files);
Upvotes: 0
Reputation: 67505
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>
Upvotes: 1
Reputation: 36599
Use
bracket-notation
to assign value to the object whenkey
is dynamic!
Initialize files
as object({})
, not as array
as you are expecting result as an object
Note: Use .substr(1);
if you are suppose to remove #(first character)
from string.
var files = {};
$('#filenames').find('a').each(function(i) {
//files[i] = $(this).attr('href').substr(1);;//For index iteration as key
files[this.id] = $(this).attr('href').substr(1); //For ID attribute as key
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="filenames">
<div>
<a id="1" class="delete" href="#1984.xls">1984.xls</a>
</div>
<div>
<a id="2" class="delete" href="#1984.xml">1984.xml</a>
</div>
</div>
Upvotes: 1
Reputation: 11502
You can do it in following way:
var files = {};
$('#filenames').find('a').each(function() {
files[$(this).attr('id')] = $(this).attr('href');
});
console.log(files);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/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>
Upvotes: 2