如何使用lodash来计算此容器中有多少个标签对象?

时间:2015-07-29 20:37:03

标签: javascript arrays object lodash

在下面的对象数组中有3个标签,你如何使用lodash来检索标签对象?

container = [Object, Object];

// container:
[
    0: Object {
        tags: [
            0: {
                term: "tag_name_1",
                term_id: 1111
            },
            0: {
                term: "tag_name_2",
                term_id: 2222
            }
        ],
        ticker: {
            name: "ticker1"
        }
    },
    1: Object {
        tags: [
            0: {
                term: "tag_name_3",
                term_id: 3333
            }
        ],
        ticker: {
            name: "ticker2"
        }
    }
]

1 个答案:

答案 0 :(得分:1)

只需pluck'em&弄平:

var container = [
    {
        tags: [
            {
                term: "tag_name_1",
                term_id: 1111
            },
            {
                term: "tag_name_2",
                term_id: 2222
            }
        ],
        ticker: {
            name: "ticker1"
        }
    },
    {
        tags: [
            {
                term: "tag_name_3",
                term_id: 3333
            }
        ],
        ticker: {
            name: "ticker2"
        }
    }
];

var p = _(container).pluck('tags').flattenDeep();

alert(JSON.stringify(p, null, ' '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>