How to create array of objects with key & value from DOM element?

Tags: ,



How can I create an array of objects like this?

let cars = [
  {
    color: "purple",
    type: "minivan",
    capacity: 5
  },
  {
    color: "red",
    type: "suv",
    capacity: 5
  },
  {
    ...
  },
  ...
]

let cars = [];

$(".car").each(function() {

var color = $(this).data('color');
var type = $(this).data('type');
var capacity = $(this).data('capacity');
  cars.push();
});
.car {
  background: gold;
  padding: 10px;
  margin: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="car" data-color="purple" data-type="minivan" data-capacity="5"> Car 1</div>
<div class="car" data-color="red" data-type="suv" data-capacity="5"> Car 2</div>
<div class="car" data-color="green" data-type="sedan" data-capacity="2"> Car 3</div>

Answer

You are doing it right, you need to push the elements objects into the array

let cars = [];

$(".car").each(function() {

var color = $(this).data('color');
var type = $(this).data('type');
var capacity = $(this).data('capacity');
  cars.push({color, type, capacity});
});

console.log(cars)
.car {
  background: gold;
  padding: 10px;
  margin: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="car" data-color="purple" data-type="minivan" data-capacity="5"> Car 1</div>
<div class="car" data-color="red" data-type="suv" data-capacity="5"> Car 2</div>
<div class="car" data-color="green" data-type="sedan" data-capacity="2"> Car 3</div>


Source: stackoverflow