You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从DOM元素的键值对创建对象数组?附实现示例

从DOM元素的data属性生成目标对象数组的解决方案

很简单,你只需要完善cars.push()的部分,把提取到的属性包装成对象推入数组就行。甚至还可以用jQuery的API简化代码,让逻辑更清晰。

方案一:基于你现有代码的修改

直接把提取的三个属性组成对象,推入数组:

let cars = [];
$(".car").each(function() {
  var color = $(this).data('color');
  var type = $(this).data('type');
  // 注意:jQuery的data()方法会自动将数字类型的data属性值转为Number类型,这里capacity会是数字5、2,而不是字符串
  var capacity = $(this).data('capacity');
  // 用ES6的对象字面量简写语法,属性名和变量名一致时可以省略冒号和值
  cars.push({ color, type, capacity });
});

方案二:更简洁的写法

jQuery的data()方法如果不传递参数,会返回当前元素所有data属性组成的对象。结合map()和get()方法,可以一行完成数组生成:

// map()遍历每个.car元素,返回对应的data对象,get()将jQuery集合转为普通数组
let cars = $(".car").map(function() {
  return $(this).data();
}).get();

完整可运行代码示例

<!DOCTYPE html>
<html>
<head>
  <style>
    .car {
      background: gold;
      padding: 10px;
      margin: 6px;
    }
  </style>
</head>
<body>
  <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>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    // 用简洁方案的话
    let cars = $(".car").map(function() {
      return $(this).data();
    }).get();

    // 测试输出,看看结果是否符合预期
    console.log(cars);
  </script>
</body>
</html>

运行后,cars数组就会和你期望的结构完全一致啦~

内容的提问来源于stack exchange,提问作者Behseini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:17:51