How to output a list of data from an array using comma JS?

Advertisements

Help a beginner in js There is data in the form of:

[
    {
        "cmm": "erl",
        "pk": {
            "from": "",
            "to": "",
            "dt": "ZF"
        },
        "status": true,
        "mk": false,
        "rps": {
            "cll": "B90BD"
        }
    },
    {
        "cmm": "erl",
        "pk": {
            "from": "",
            "to": "",
            "dt": "7E"
        },
        "status": true,
        "mk": false,
        "rps": {
            "cll": "2E147FA3"
        }
    },
        {
        "cmm": "erl",
        "pk": {
            "from": "",
            "to": "",
            "dt": "7E"
        },
        "status": true,
        "mk": false,
        "rps": {
            "cll": "2E147FA3"
        }
    }
]

I want to get a list of "cll" Comma separated. B90BD,2E147FA3,2E147FA3… I tried filtering, but I get an error.

function list(data) {
    const dtt = JSON.parse(data);
    console.log(dtt);
        const addrs = dtt.filter(function (item) {
        return item.rps;}).join(",");
        console.log(addrs);
    console.log(addrs);
        }

This command works, but I only get the data of the first element.

function createTable(data) {
    const dtt = JSON.parse(data);
    const mm = dtt[0].rps;
    var myAr = mm.ccl;
    console.log(myAr);
        }

>Solution :

I would do it like this:

function list(data) {
    const dtt = JSON.parse(data);
    const addresses = dtt
        .filter(function (item) {
            return item.rps && item.rps.cll; 
        })
        .map(function (item) {
            return item.rps.cll; 
        })
        .join(",");
    
    console.log(addresses);
}

First we filter your data to only keep the elements that have rps and cll within rps. Then we use map() to create a new array of only the values of rps.cll. Finally we join the values with a comma and print the result to console.

Assuming you have your data in a variable like this:

const jsonData = `
[
    {
        "cmm": "erl",
        "pk": {
            "from": "",
            "to": "",
            "dt": "ZF"
        },
        "status": true,
        "mk": false,
        "rps": {
            "cll": "B90BD"
        }
    },
    {
        "cmm": "erl",
        "pk": {
            "from": "",
            "to": "",
            "dt": "7E"
        },
        "status": true,
        "mk": false,
        "rps": {
            "cll": "2E147FA3"
        }
    },
    {
        "cmm": "erl",
        "pk": {
            "from": "",
            "to": "",
            "dt": "7E"
        },
        "status": true,
        "mk": false,
        "rps": {
            "cll": "2E147FA3"
        }
    }
]
`;

You can call the function like this:

list(jsonData);      // Output: B90BD,2E147FA3,2E147FA3

Leave a ReplyCancel reply