Javascript多维数组键值

时间:2017-01-17 10:00:07

标签: javascript arrays json ajax multidimensional-array

我正在对JSON执行AJAX请求并获取以下代码作为响应:

{
  total: "1",
  items: [
    {
      id: 43,
      title: "ThisIsTheTitle",
      promoted: false,
      sticky: false,
      weight: 10,
      created: {
        timestamp: 1482054,
        formatted: "17/01/2017"
      },
      url: "http://...",
      airdate: {
        timestamp: 1484980,
        formatted: "17/01/2017"
      },
      video: {
        id: 43,
        number_of_views: 1,
        duration: {
          seconds: 50,
          formatted: "00:00"
        },
        required_login: false
      },
      program: {
        id: 25,
        url: "http://...",
        title: "ProgrammaTitel"
      },
      image: {
        uri: "public://...",
        full: "http://..."
      },
      tags: [
        {
          id: "4",
          name: "Map"
        },
        {
          id: "7",
          name: "Aflevering2"
        }
        ]
    }
  ]
}

现在我将这些数据推送到我自己的JSArray中。请注意,现在只有1个响应项,但会添加更多。

我想根据对象标记的名称检索特定对象数据 (item > tags > name = 'Aflevering2')

所以我想要标记名为'Aflevering2'的对象中的数据。

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以找到filter()some()组合的项目:

obj.items.filter(v => v.tags.some(k => k.name === 'Aflevering2'));



let obj = {
    total: "1",
        items: [
    {
        id: 43,
        title: "ThisIsTheTitle",
        promoted: false,
        sticky: false,
        weight: 10,
        created: {
            timestamp: 1482054,
            formatted: "17/01/2017"
        },
        url: "http://...",
        airdate: {
            timestamp: 1484980,
            formatted: "17/01/2017"
        },
        video: {
            id: 43,
            number_of_views: 1,
            duration: {
                seconds: 50,
                formatted: "00:00"
            },
            required_login: false
        },
        program: {
            id: 25,
            url: "http://...",
            title: "ProgrammaTitel"
        },
        image: {
            uri: "public://...",
            full: "http://..."
        },
        tags: [
            {
                id: "4",
                name: "Map"
            },
            {
                id: "7",
                name: "Aflevering2"
            }
        ]
    }
]
}

let items = obj.items.filter(v => v.tags.some(k => k.name === 'Aflevering2'));
console.log(items);