简体   繁体   中英

How can I transform this object in React-Native?

I have a object like so

 { -L1Rm6VbfLLyFJ3Qi6K: {city: "Tokyo", date: "26-08-2004" } }

and I want to transform this object like this:

 { id:"-L1Rm6VbfLLyFJ3Qi6K", city: "Tokyo", date: "26-08-2004" }

How can I do that? Thank you...

You can take Object.entries and map them in desired format.

 let obj = { '-L1Rm6VbfLLyFJ3Qi6K': {city: "Tokyo", date: "26-08-2004" } } let op = Object.entries(obj).map(([key,value]) => ({ id: key, ...value, })) console.log(op)

if there is only one object/index you can access in this way.

 let obj = { '-L1Rm6VbfLLyFJ3Qi6K': {city: "Tokyo", date: "26-08-2004" } } let op = Object.entries(obj).map(([key,value]) => ({ id: key, ...value, })) console.log(op[0])

If the object going to be one key value then use this, otherwise, like @Code Maniac suggested, you should use a map or forEach

 const obj = { '-L1Rm6VbfLLyFJ3Qi6K': {city: "Tokyo", date: "26-08-2004" } } const newobj = { id: Object.keys(obj)[0], ...obj[Object.keys(obj)] } console.log(newobj)

Maybe you looking like this way?

 const obj1 = { "-L1Rm6VbfLLyFJ3Qi6K": {city: "Tokyo", date: "26-08-2004" } } const obj2 = {} for (const id in obj1) { Object.assign(obj2, { id, ...obj1[id] }) } console.log(obj2);

or reusing old object with this way?

 const obj1 = { "-L1Rm6VbfLLyFJ3Qi6K": {city: "Tokyo", date: "26-08-2004" } } for (const id in obj1) { Object.assign(obj1, { id, ...obj1[id] }) delete obj1[id]; } console.log(obj1);

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