简体   繁体   中英

Map Object of Objects without knowing Object Key - React Native

I need to get "primarySprayCanRGB" and "primarySprayCanHighLightRGB" from each individual object in the object and add them to the array. But I don't know the individual object keys. => The paint names are different. I'm working in React Native

for example get: [["#000000", "#131313"],["#292b2d", "#7b7d80"],["#6b0913", "#bc3038"],...]

The code I have so far, to get the data to add to the array, but the code returns only the first oibject because the id is not incremented :

//data == object.paints
//loadinga == false => when data is ready to use
{!loadinga && data.map((object,id) => console.log(object[id].primarySprayCan.primarySprayCanRGB))}

Link to JSON file:

https://cdn.imagin.studio/getPaintSwatches?customer=imagin&make=tesla&paints=pbsb,pmng,ppmr,ppsb,ppsw

You can map through the values of the paints objects using the Object.values() function. then select the values you want to extract from it.

Object.values(data).map({ primarySprayCan } => {
    return [ primarySprayCan['primarySprayCanRGB'], primarySprayCan['primarySprayCanHighLightRGB'] ]
});

you can do it like this

 const extractData = data => Object.values(data.paints).map(({primarySprayCan}) => [primarySprayCan.primarySprayCanRGB, primarySprayCan.primarySprayCanHighLightRGB]) const data = { "make": "tesla", "paints": { "pbsb": { "paintId": "pspc0004", "paintDescription": "", "primarySprayCan": { "sprayCanId": "spc0004", "paintType": "uni", "primarySprayCanRGB": "#000000", "primarySprayCanHighLightRGB": "#131313", "colourCluster": "black" } }, "pmng": { "paintId": "pspc0239", "paintDescription": "", "primarySprayCan": { "sprayCanId": "spc0239", "paintType": "mic", "primarySprayCanRGB": "#292b2d", "primarySprayCanHighLightRGB": "#7b7d80", "colourCluster": "grey" } }, "ppmr": { "paintId": "pspc0107", "paintDescription": "", "primarySprayCan": { "sprayCanId": "spc0107", "paintType": "mic", "primarySprayCanRGB": "#6b0913", "primarySprayCanHighLightRGB": "#bc3038", "colourCluster": "red" } }, "ppsb": { "paintId": "pspc0266", "paintDescription": "", "primarySprayCan": { "sprayCanId": "spc0266", "paintType": "mic", "primarySprayCanRGB": "#101b47", "primarySprayCanHighLightRGB": "#254e9d", "colourCluster": "blue" } }, "ppsw": { "paintId": "pspc0109", "paintDescription": "", "primarySprayCan": { "sprayCanId": "spc0109", "paintType": "pearl", "primarySprayCanRGB": "#b4b4b4", "primarySprayCanHighLightRGB": "#b4b4b4", "colourCluster": "grey" } } } } console.log(extractData(data))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM