如果与另一个列值匹配,则返回json数组的列唯一值

时间:2019-07-01 01:26:48

标签: javascript nuxt.js

我正在研究NuxtJs,并且当与其他列的值匹配时,我必须从json数据列返回一个列表数组

以下代码从该列返回所有唯一值名称。但是当专辑名称仅与“ BAD” /“ Thriller”匹配时,我想获得唯一的值名称

getNameList(){
            var lookup = {};
            var items = this.testdata.songs;
            var result_name = [];
            for (var item, i = 0; item = items[i++];) {
                    var unique_name = item.name;
                    if (!(unique_name in lookup)) {
                        lookup[unique_name] = 1;
                        result_name.push(unique_name);
                    }
            }
            return result_name
}

请帮我一些代码

json数据文件名“ testdata.json”

{
    "songs": [
    {
        "id": "1",
        "name": "Thriller",
        "album": "Thriller"
    },
    {
        "id": "2",
        "name": "Smooth Criminal",
        "album": "BAD"
    },
    {
        "id": "3",
        "name": "Thriller",
        "album": "Thriller"
    },
    {
        "id": "4",
        "name": "Smooth Criminal",
        "album": "BAD"
    },
    {
        "id": "5",
        "name": "BAD",
        "album": "BAD"
    },
    {
        "id": "6",
        "name": "Billy Jean",
        "album": "Thriller"
    },
    {
        "id": "7",
        "name": "BAD",
        "album": "BAD"
    },
    {
        "id": "8",
        "name": "Smooth Criminal",
        "album": "BAD"
    },
    {
        "id": "9",
        "name": "BAD",
        "album": "BAD"
    },
    {
        "id": "10",
        "name": "Billy Jean",
        "album": "Thriller"
    },
    {
        "id": "11",
        "name": "Smooth Criminal",
        "album": "BAD"
    },
    {
        "id": "12",
        "name": "Beat It",
        "album": "Thriller"
    },

    {
        "id": "13",
        "name": "Billy Jean",
        "album": "Thriller"
    },
  ]
}

我是Java和nuxtjs的新手。我在上面的脚本代码之间尝试了几个if语句,但是对我没有任何作用。

1 个答案:

答案 0 :(得分:0)

您可以按专辑名称过滤数组,并使用Set获得唯一的数组值。

function getNameList(testdata){
  const filteredArray = testdata.songs
    .filter(item => item.album === 'BAD' || item.album === 'Thriller');
  return [...new Set(filteredArray.map(item => item.name))];
}

const a = {"songs":[{"id":"1","name":"Thriller","album":"Thriller"},{"id":"2","name":"Smooth Criminal","album":"BAD"},{"id":"3","name":"Thriller","album":"Thriller"},{"id":"4","name":"Smooth Criminal","album":"BAD"},{"id":"5","name":"BAD","album":"BAD"},{"id":"6","name":"Billy Jean","album":"Thriller"},{"id":"7","name":"BAD","album":"BAD"},{"id":"8","name":"Smooth Criminal","album":"BAD"},{"id":"9","name":"BAD","album":"BAD"},{"id":"10","name":"Billy Jean","album":"Thriller"},{"id":"11","name":"Smooth Criminal","album":"BAD"},{"id":"12","name":"Beat It","album":"Thriller"},{"id":"13","name":"Billy Jean","album":"Thriller"}]};

console.log(getNameList(a));