I am trying to send an object to an api and my object contains arrays that I want to turn into strings. However I am having trouble returning the new object with the arrays turned to strings. My goal is to have a copy of the original object with all the arrays turned into strings.
const object1 = {
a: ["TX", "CA", "LA"],
b: 42,
c: false
d: []
};
for (const [key, value] of Object.entries(object1)){
if(Array.isArray(object1[key]) && object1[key].length > 0){
object1[key].toString()
}
}
console.log(object1)
//returns the original object without `a` as string
CodePudding user response:
You are not assigning the new value to anything, so it is being lost with each loop. Try:
object1[key] = object1[key].toString()
const object1 = {
a: ["TX", "CA", "LA"],
b: 42,
c: false,
d: []
};
for (const [key, value] of Object.entries(object1)){
if(Array.isArray(object1[key]) && object1[key].length > 0){
object1[key] = object1[key].toString()
}
}
console.log(object1)
//returns the original object without `a` as string
This way with every for loop, you reassign object1[key] to object1[key].toString()
CodePudding user response:
Use join on the arrays to form strings.
const object1 = {
a: ["TX", "CA", "LA"],
b: 42,
c: false,
d: []
};
for (const [key, value] of Object.entries(object1)){
if(Array.isArray(value)) {
object1[key] = value.join(',');
}
}
console.log(object1)
If you need to get arrays back later, use split.
CodePudding user response:
You should use join(",")
const object1 = {
a: ["TX", "CA", "LA"],
b: 42,
c: false,
d: []
};
for (const [key, value] of Object.entries(object1)){
if(Array.isArray(object1[key]) && object1[key].length > 0){
object1[key] = object1[key].join(",")
}
}
console.log(object1)
CodePudding user response:
First, add a ,
after false
. Then in the if
statement change:
object1[key].toString();
To:
object1[key] = value.toString();
DEMO
const object1 = {
a: ["TX", "CA", "LA"],
b: 42,
c: false,
d: []
};
for (const [key, value] of Object.entries(object1)){
if(Array.isArray(value) && value.length > 0) {
object1[key] = value.toString();
}
}
console.log(object1)
NOTE
Pursuant to My goal is to have a copy of the original object with all the arrays turned into strings, if you'd like to convert []
to ""
, then remove && object1[key].length > 0
from the if
condition.
const object1 = {
a: ["TX", "CA", "LA"],
b: 42,
c: false,
d: []
};
for (const [key, value] of Object.entries(object1)){
if(Array.isArray(value)) {
object1[key] = value.toString();
}
}
console.log(object1)