Francis F
Francis F

Reputation: 3285

Get array of JSON keys in react native

I have a JSON data in the format

[{
    "Heading1": [{
        "questionID": "q1",
        "questionTitle": "Question 1",
        "question": "This is question1",
        "status": 0,
        "files": [],
        "uploadType": "none"
    }, {
        "questionID": "q2",
        "questionTitle": "Question 2",
        "question": "This is question2",
        "status": 0,
        "files": [],
        "uploadType": "none"
    }]
}, {
    "Heading2": [{
        "questionID": "q3",
        "questionTitle": "Question 11",
        "question": "This is a question11",
        "status": 0,
        "files": [],
        "uploadType": "none"
    }]
}, {
    "Heading3": [{
        "questionID": "q4",
        "questionTitle": "Question 1",
        "question": "This is a question",
        "status": 0,
        "files": [],
        "uploadType": "none"
    }]
}]

I'm trying to get all the titles in a format like [{"Title":"Heading1"},{"Title":"Heading2"},{"Title":"Heading3"}]

How should I go about it?

Upvotes: 2

Views: 6170

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073978

First, if you really have JSON (e.g., your starting point is a string, such as from an ajax response), you parse it via JSON.parse to get an array of objects. Then you loop the array and get the only key from each of those top-level objects via Object.keys(x)[0] and map that to an array of objects in the form you want:

const json = '[{"Heading1":[{"questionID":"q1","questionTitle":"Question 1","question":"This is question1","status":0,"files":[],"uploadType":"none"},{"questionID":"q2","questionTitle":"Question 2","question":"This is question2","status":0,"files":[],"uploadType":"none"}]},{"Heading2":[{"questionID":"q3","questionTitle":"Question 11","question":"This is a question11","status":0,"files":[],"uploadType":"none"}]},{"Heading3":[{"questionID":"q4","questionTitle":"Question 1","question":"This is a question","status":0,"files":[],"uploadType":"none"}]}]';
const parsed = JSON.parse(json);
const result = parsed.map(entry => {
  return {Title: Object.keys(entry)[0]};
});
console.log(result);

The map callback can be a concise arrow function, but I thought using the verbose form above would be clearer. The concise form would be:

const result = parsed.map(entry => ({Title: Object.keys(entry)[0]}));

Note that using Object.keys in this way is only reliable if the objects really have just one property, as in your question. If they have more than one property, the order the properties are listed in the array from Object.keys is not defined (even in ES2015+, where properties do have an order — Object.keys is not required to follow that order [although it does on every modern engine I've tested]).

Upvotes: 1

Related Questions