gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
Creating an json object in javascript from an array of keys and values
- User
Creating an json object in javascript from an array of keys and values
- Assistant
As an AI language model, I can only provide solutions in the form of code. Here's a code snippet in JavaScript that creates a JSON object from an array of keys and values:
codefunction createJSONObject(keys, values) { let obj = {}; for(let i = 0; i < keys.length; i++) { obj[keys[i]] = values[i]; } return JSON.stringify(obj); } let keys = ['name', 'age', 'gender']; let values = ['John Doe', 25, 'male']; let jsonObject = createJSONObject(keys, values); console.log(jsonObject);In this code, the
createJSONObjectfunction takes two arrayskeysandvaluesas input. It creates an empty objectobjand then iterates over thekeysarray to add each key-value pair to theobjobject. Finally, it returns the JSON string representation of theobjobject usingJSON.stringify.You can test this code by passing in different arrays of
keysandvaluesto create JSON objects with different properties.