javascript - jQuery:从对象数据创建数组

标签 javascript jquery arrays object

问题是键和值变量都被设置为对象。如何将它们转换为文本字符串?

units = [];

$('thead th[style*="width:130px;line-height:1.2em;text-align:center"]').each(function() {

    key  = $(this).contents('')[4];
    value = $(this).contents('')[6];

    units[key] = value;

});

JSBin of problem

最佳答案

如果我正确理解您的问题,以下就是您要查找的内容。

jQuery .contents()结果是一个 jQuery 对象。因此,您应该仅从中过滤文本节点,然后获取其文本。 (注意:我已使用 .trim() 清除任何多余的空格/换行符)。

jQuery:

units = [];

$('thead th[style*="width:130px;line-height:1.2em;text-align:center"]').each(function () {
    key = $(this).contents().filter(function () {
        return this.nodeType === 3;
    }).eq(2).text().trim();
    value = $(this).contents().filter(function () {
        return this.nodeType === 3;
    }).eq(3).text().trim();
    units[key] = value;
});
//console.log(units);

控制台输出:

[pat (1" sq, 1/3" high): "5g", tbsp: "14.2g", cup: "227g", stick: "113g"]

Working Demo

注意: 正如其他人在评论中指出的那样,我也不建议在选择器中使用内联 CSS。您可以将它们放入 CSS 类中,然后在选择器中使用该类,例如 this .

关于javascript - jQuery:从对象数据创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18863834/

相关文章:

c# - 检查值是否在数组中 (C#)

javascript - 反转数组,循环中的 pop 方法未弹出完成

php - 错误的 json 数组 Python post 请求到 PHP

javascript - 注销时 vuex 为空状态

javascript - 如何停止 JavaScript 中的递归函数?

javascript - 如何使对象 float 在不同标签的右下角

jquery - 性能最佳的 JQuery 图表插件有哪些?

javascript - 如何返回 AngularJS 函数的 $http 响应?

php - mysql 搜索查询和使用 php 或 javascript 的分页

javascript - 将模板添加到 div 内的 img 前面