Extract data from JSON as an example

Asked

Viewed 227 times

1

I have the following object JSON which is returned after database query:

{
    data: {
        act: "3 ",
        searchType: "2",
        searchData: "33014421"
    },
    convicts: {
    count: 2,
    rows: [
            {
                idConvict: 7
            },
            {
                idConvict: 23
            }
        ]
    }
}

How to extract only the data from the field idConvict so that I return a array [7, 23]?

  • 2

    post the code of what you’ve tried to do?

2 answers

2


With map on the way json.convicts.rows, drawing only the value of idConvict new is generated array [7, 23], example:

const json = {
    data: {
        act: "3 ",
        searchType: "2",
        searchData: "33014421"
    },
    convicts: {
    count: 2,
    rows: [
            {
                idConvict: 7
            },
            {
                idConvict: 23
            }
        ]
    }
};



const ids = json.convicts.rows.map(x => {
  return x.idConvict;
});

console.log(ids);

0

let json = {
    data: {
        act: "3 ",
        searchType: "2",
        searchData: "33014421"
    },
    convicts: {
    count: 2,
    rows: [
            {
                idConvict: 7
            },
            {
                idConvict: 23
            }
        ]
    }
}

let ids_convict = json['convicts'].rows
    .forEach( e => {
        console.log(e.idConvict);
});



let outra_forma = json.convicts.rows
.forEach( e => {
    console.log(e.idConvict);
})


let mais_outra_forma = json.convicts.rows
    .forEach( e => console.log(e.idConvict));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.