如何创建key =>在Javascript中集合对象中的值数组

时间:2014-10-30 20:34:34

标签: javascript jquery

我有这个HTML表格:

<table class="table table-condensed">
    <thead>
        <tr>
            <th><input type="checkbox" id="toggleCheckboxSelFabricante" name="toggleCheckboxSelFabricante"></th>
            <th>Fabricante</th>
        </tr>
    </thead>
    <tbody id="selFabricanteBody">
        <tr>
            <td><input type="checkbox" name="selChkFabricante" id="selChkFabricante3" value="3"></td>
            <td>Eos est ipsam.</td>
        </tr>
    </tbody>
</table>

我需要为key => value var创建manufacturerColl,其中id是每个选中复选框的值(表格上的第一个td),name是文本第二栏,但不知道如何。这就是我在我的代码中所做的:

var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
                checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
                manufacturerColl = [],
                modelBranchManufacturerCollection;


        for (var j = 0; j < checkedManufacturers.length; j++) {
            manufacturerColl.push(checkedManufacturers[j].value);
        }

        for (var i = 0; i < checkedModelBranch.length; i++) {
            modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
            if (modelBranchManufacturerCollection) {
                for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
                    $("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).html(modelBranchManufacturerCollection.manufacturerKeyCollection[k] + '<br/>');
                }
            }
        }

我需要的其他单词是manufacturerColl个和id =&gt; name,例如:

manufacturerColl[] = {
  id: someId,
  name: someName
};

我不确定但也许这可行:

   // move foreach selected checkbox and get the needed
   for (var j = 0; j < checkedManufacturers.length; j++) {
        manufacturerColl.push({
            id: checkedManufacturers[j].value,
            name: "" // how do I get the value on the second column?
        });
    }

这是正确的方法吗?如何在每次迭代时获取第二列的值?

方法

我不知道这是否完整,但是我已经完成了它并且它是错误的。见代码:

var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
                checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
                // I added this var to get all the names 
                checkedManufacturersName = $("#selFabricanteBody").find("input[type='checkbox']:checked").parent().next('td').text(),
                manufacturerColl = [],
                modelBranchManufacturerCollection;


        for (var j = 0; j < checkedManufacturers.length; j++) {
            manufacturerColl.push({
                id: checkedManufacturers[j].value,
                // Here I'm tying to put the entire name but get only the first character
                name: checkedManufacturersName[j]
            });
        }

        for (var i = 0; i < checkedModelBranch.length; i++) {
            modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
            if (modelBranchManufacturerCollection) {
                //$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).siblings().attr("rowspan", modelBranchManufacturerCollection.manufacturerKeyCollection.length);

                for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
                    // then I render the name attribute from the collection
                    $("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).append((modelBranchManufacturerCollection.manufacturerKeyCollection)[k].name + '<br/>');
                }
            }
        }

为什么我只插入/获取第一个字符而不是完整字符串?

2 个答案:

答案 0 :(得分:1)

//由于您的输入和文本都包含在td元素中

在代码中:

var checked = $('#selFabricanteBody').find('input[type="checkbox"]:checked');
var arr = [], j = checked.length, item;

while(j--) {
    item = list[j];
    //gets the text from the next child, assumes its the text
    //if the text is before checkbox, use previousSibling
    arr.push({id: item.value, name: item.parentNode.nextSibling.nodeValue});
}

答案 1 :(得分:0)

这是我用来创建一个对象,用于发送到一个控制器方法,该方法正在寻找一个类/模型作为参数:

function ExtractModel(array) {
var modelString = '';
var model = {};
//var array = arrayString.split('&');
var isObjectModel = $.isPlainObject(array);
if (!isObjectModel) {
    $(array).each(function (index, element) {
        var typeId = element.split('=')[0];
        var val = element.split('=')[1];
        if (element == null) { } else {
            model[typeId] = (val);
        }
    });
} else {
    model = array;
}
return model;

};

所以,有了这个,我正在获取一个url参数字符串并从中创建一个对象;参数字符串是从序列化表单生成的。 &#34;模型&#34;自动创建由&#34; typeId&#34;;表示的属性。如果&#34; typeId&#34; =&#34;你好&#34;然后将创建一个新属性或对象项,名为&#34; hello&#34; (model.hello会给你一个价值)。您可以使用相同的逻辑循环遍历页面上的元素,以使用倍数填充对象。确保设置变量&#34; modelBranchManufacturerCollection&#34;等于{},然后设置插入新值的索引。

这应该做你想要的:

 var ids = [1, 2, 3, 4, 5, 6]
var names = ['a', 'b', 'c', 'd', 'e', 'f']

var mainObj = {};

$(ids).each(function (index, element) {
    var miniObj = {};
    miniObj['id'] = ids[index];
    miniObj['name'] = names[index];
    mainObj[index] = miniObj;
});

返回6项id和name。