简体   繁体   中英

How to convert a React array to a JSON object with same key and value?

I have an array of values in my React app [profile1, profile2, profile3] read from a database and I need to convert these to a json object that can be used in a third party component. The resultant json needs to be:

{profile1: "profile1", profile2: "profile2", profile3: "profile2"}

I am unfamiliar with JavaScript and React.

 const object = {}; const array = ["one", "two", "three"]; array.forEach(v => object[v] = v); console.log(object);

I would suggest doing something like this

 const profiles = ['profile1', 'profile2', 'profile3']; let obj = {}; profiles.forEach(profile => obj[profile] = profile); console.log(obj);

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