Cunning Cunning - 6 months ago 9
HTML Question

Creating an object using filtered element attributes in JavaScript

I have a dynamically created

<div/>
area like this

<div class="canvas">
<div id="1" data-level="0" data-tag="a"></div>
<div id="2" data-level="0" data-tag="b">
<div id="3" data-level="1" data-tag="b">
<div id="4" data-level="2" data-tag="a"></div>
</div>
<div id="5" data-level="1" data-tag="a"></div>
</div>
<div id="6" data-level="0" data-tag="b"></div>
</div>


I want to create an object to pass in an ajax call containing ids, tags and texts on each
<div/>
element with
[level="0"]
.

Something like this

var outObj = jQuery('div.canvas > div[level="0"]')
.objectFromFilter([
{attr: 'id', prop: 'id'},
{attr: 'data-tag', prop: 'tag'}
]);
console.log(outObj);


That would result in

[
{ id: "1", tag: "a" },
{ id: "2", tag: "b" },
{ id: 6, tag: "b" }
]

Answer

You can do it using .map()

Try like this

var outObj = $('div.canvas > div[data-level="0"]').map(function() {
  return {
    id: $(this).attr("id"),
    tag: $(this).data("tag")
  };

});
console.log(outObj);

JSFIDDLE