简体   繁体   English

如何使用JavaScript制作匹配元素的对象

[英]How to make object of match element using javascript

I have list of pax in my HTML. 我的HTML中有pax列表。 I need to make an object containing pax type and their count. 我需要制作一个包含pax类型及其计数的对象。 for instance: {adult:3, child:2} fiddle 例如: {adult:3, child:2} 小提琴

var obj='{';
$('.pax').find('div').each(function(i,val){
   var pax= $(this).text();
   obj+= $(this).text();
        obj+=':';
        obj+=i;
        obj+=','

})

obj+="}"

console.log(obj) console.log(obj)

var obj = {};
$('.pax div').each(function(i) {
    var pax = $(this).text();
    obj[pax] = i;
});

However, with your current markup this doesn't make any sense - objects cannot have multiple values for the same key unless you store an array: 但是,使用您当前的标记没有任何意义-除非您存储数组,否则对象不能为同一键具有多个值:

var obj = {};
$('.pax div').each(function(i) {
    var pax = $(this).text();
    if (!(pax in obj)) {
        obj[pax] = [];
    }
    obj[pax].push(i);
});

If you don't need the indexes but the count for each type, see this answer instead . 如果您不需要索引,但需要每种类型的计数,请改为查看此答案

If you need a JSON string in the end, use JSON.stringify(obj) . 如果最后需要JSON字符串,请使用JSON.stringify(obj)

Try 尝试

var obj = {};

$('.pax').find('div').each(function (i, val) {
    var pax = $.trim($(this).text());
    obj[pax] = (obj[pax] || 0) + 1;
})

Demo: Fiddle 演示: 小提琴

Then use JSON.stringify() if you want a string representation of the value 如果您想要该值的字符串表示形式,请使用JSON.stringify()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM