2

我想得到一个像这样的对象:

{"Red 1":53,"Blue 2":26,"Green 3":25}

从以下示例:

试图将 .each 内部的数据推送到对象,但它是多维的,我不知道如何实现这一点:

//html
<div class="test">
    <div class="color">Red 1</div>
    <div class="value">53</div>
</div>
<div class="test">
    <div class="color">Blue 2</div>
    <div class="value">26</div>
</div>
<div class="test">
    <div class="color">Green 3</div>
    <div class="value">25</div>
</div>

//js
var dataPoints = {}; 
var colorTitle = '';
var colorValue = '';

$('.test').each(function(index) {
    colorTitle = $(this).find('.color').html();
    colorValue = $(this).find('.value').html();
    dataPoints.push({colorTitle:colorValue});
});

上面的代码显然不起作用,但我想基本上展示我正在尝试做的事情。

也尝试过这种方法:

dataPoints[index][colorTitle] = colorValue;

这也不起作用。可能一起遗漏了一些东西,但任何帮助表示赞赏!谢谢

4

5 回答 5

6

这将做到:

var data = {};
$(".test").each(function() {
   var key = $(this).find(".color").text();
   var value = $(this).find(".value").text();

   data[key] = value;
};
于 2012-06-08T20:59:21.233 回答
3

处理对象时使用正确的键/值分配。对象没有push方法。

$('.test').each(function(index) {
    dataPoints[$(this).find(".color").text()] = $(this).find(".value").text();
});
于 2012-06-08T20:58:57.010 回答
2

实际上,您离正确并没有那么远,但是将其视为对象而不是数组-

var dataPoints = new Object(); 
var colorTitle = '';
var colorValue = '';

$('.test').each(function(index) {
    colorTitle = $(this).find('.color').html();
    colorValue = $(this).find('.value').html();
    dataPoints[colorTitle] = colorValue;
});

//test it!
alert(JSON.stringify(dataPoints));
于 2012-06-08T21:09:28.403 回答
2

它不是多维的。它甚至不是一个数组。

push用于数组。

在 an中,object您可以添加一个键/值,例如obj["key"]= valueor obj.key = value

所以,试试这个

var dataPoints = {};  
$('.test').each(function(index) {
    var $this = $(this);
    dataPoints[$this.find('.color').html()]= $this.find('.value').html();
});
于 2012-06-08T21:29:00.917 回答
0

您缺少该each()函数的右括号。对象{}也没有 push 方法。

如果要维护元素列表,请使用数组[]

于 2012-06-08T20:59:20.113 回答