Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向多维对象推送_Javascript_Jquery - Fatal编程技术网

Javascript 向多维对象推送

Javascript 向多维对象推送,javascript,jquery,Javascript,Jquery,我想以这样一个对象结束: {"Red 1":53,"Blue 2":26,"Green 3":25} 根据以下示例: 试图从内部推送数据。每个都推送到对象,但它是多维的,我不确定如何实现: //html <div class="test"> <div class="color">Red 1</div> <div class="value">53</div> </div> <div class="tes

我想以这样一个对象结束:

{"Red 1":53,"Blue 2":26,"Green 3":25}
根据以下示例:

试图从内部推送数据。每个都推送到对象,但它是多维的,我不确定如何实现:

//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});
});

这也不行。可能一起错过了一些东西,但任何帮助都是非常感谢的!谢谢

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

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

each()
函数缺少一个右括号。另外,对象
{}
没有push方法

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

,这样可以:

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

   data[key] = value;
};

事实上,你的方法离正确还不远,但是把它看作一个对象,而不是数组-

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));

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

push
用于阵列

对象中
可以添加一个键/值,如
obj[“key”]=value
obj.key=value

那么,试试这个

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

您考虑过使用数组吗?它具有顺序索引和内置的
.push
。您可以让它与
var dataPoints=[]
@Esailija一起工作,OP希望这样结束
{“红色1”:53,“蓝色2”:26,“绿色3”:25}
我已经更新了我的答案,只是注意到您想要的最终结果是什么,无需为此调用jQuery两次。。。您只能调用它一次并像这样缓存它:var$this=$(this);
var dataPoints = {};  
$('.test').each(function(index) {
    var $this = $(this);
    dataPoints[$this.find('.color').html()]= $this.find('.value').html();
});