Somename Somename - 3 years ago 140
React JSX Question

Do I need to convert this Array in Objects?

My

data
is an array that I'm converting into a
key:value
(not sure if this is what it's called) type.

Data:

[
{
"id": 1,
"title": "Name 01",
"tags": [
"TAG1",
"TAG4",
"TAG2"
]
},
{
"id": 2,
"title": "Name 02",
"tags": [
"TAG4",
"TAG3"
]
},
{
"id": 3,
"title": "Name 03",
"tags": [
"TAG1"
]
}
]


I'm converting this into :

result = data.map(a => ({ [a.id]: a }));


So I'm getting:

Result:

[
{
"1": {
"id": 1,
"title": "Post1 T1 T2 T4",
"tags": [
"TAG1",
"TAG4",
"TAG2"
]
}
},
{
"2": {
"id": 2,
"title": "Post1 T3 T4",
"tags": [
"TAG4",
"TAG3"
]
}
},
{
"3": {
"id": 3,
"title": "Post3 with No Tags",
"tags": [
"TAG1"
]
}
}
]


How can I map the results and show in a
View/Text
?

I tried:

Object.keys(results).map((result, idx) => {
return(
<View key={idx}>
<Text>{result.title}</Text>
</View>
)
});


But I'm getting an error :
Cannot read property 'map' of undefined.


Do I need to convert the results to an object and only then I'll be able to use
Object.keys
. If yes, how do I convert the entire result in an Object like this:

Results:

{
{
"1": {
"id": 1,
"title": "Post1 T1 T2 T4",
"tags": [
"TAG1",
"TAG4",
"TAG2"
]
}
},
{
"2": {
"id": 2,
"title": "Post1 T3 T4",
"tags": [
"TAG4",
"TAG3"
]
}
},
{
"3": {
"id": 3,
"title": "Post3 with No Tags",
"tags": [
"TAG1"
]
}
}
}


The reason I'm doing this is to target the id for a reducer dispatched action:

switch (action.type) {
case "INC_NUM":
const newState = {...state};
newState[action.payload].nubmer++;
return newState;

Answer Source

It sounds like you just want to be able to quickly find the object that has a given id value. Rather than "convert" your data, I'd suggest you just make a map so you can look up any object by id.

let data = [
    {
        "id": 1,
        "title": "Name 01",
        "tags": [
            "TAG1",
            "TAG4",
            "TAG2"
        ]
    },
    {
        "id": 2,
        "title": "Name 02",
        "tags": [
            "TAG4",
            "TAG3"
        ]
    },
    {
        "id": 3,
        "title": "Name 03",
        "tags": [
            "TAG1"
        ]
    }
];

// create a map with id as the key, object as the value
let map = new Map();
data.forEach(obj => {
   map.set(obj.id, obj);
});

// look up a given id
console.log(map.get(3));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download