2

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>

2 Answers 2

2

To achieve what you require you can use map() to build an array from all the data attributes on the elements:

let cars = $('.car').map((i, el) => el.dataset).get();
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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.