Reputation: 595
I need to add single quotes to all the values in an object that looks like this:
{name: "testUser", type: "regular"}
The object needs to look like the following:
{name: "'testUser'", type: "'regular'"}
I'm using Object.values
to achieve this:
Object.values(targetObject).map(value => value = `'${value}'`)
Except it's not exactly updating targetObject
. What would be the correct way to achieve this?
Upvotes: 2
Views: 3654
Reputation: 2042
You can you for..in
to loop through properties of the object.
const obj = {name: "testUser", type: "regular"}
for (let k in obj){
obj[k] = `'${obj[k]}'`
}
console.log(obj)
Upvotes: 1
Reputation: 29115
You can use Object.entries
to iterate through all the entries in the object and update them:
const obj = {name: "testUser", type: "regular"};
for (let [key, value] of Object.entries(obj)) {
obj[key] = `'${value}'`;
}
console.log(obj);
Upvotes: 1
Reputation: 386868
You could map new objects and collect them to a single object.
var object = { name: "testUser", type: "regular" },
updated = Object.assign(...Object.entries(object).map(([k, v]) => ({ [k]: `'${v}'` })));
console.log(updated);
Upvotes: 0
Reputation: 193258
To update the original object, you'll need the key. Use Object.entries()
to get the key and value, iterate with Array.forEach()
, and each key with the new value:
const targetObject = {name: "testUser", type: "regular"}
Object.entries(targetObject) // get an array of [key, value] pairs
.forEach(([k, v]) => targetObject[k] = `'${v}'`) // update the original object keys
console.log(targetObject)
Upvotes: 2