I have an object that contains key pair values of objects that are in array form:
let obj = {};
let joinedData;
obj["key1"] = ["val1", "val2"];
obj["key2"] = ["val3", "val4"];
I want to join all the values together as a string:
for (const [key, values] of Object.entries(obj)) {
joinedData = `${values.join(",")}`;
}
The expected result is "val1,val2,val3,val4"
But joinedData
is empty.
I suspect that it's because the values
are objects and not array (when I use typeof
).
How to get the expected result in this case?
CodePudding user response:
You can use Object.values
and flat
:
let obj = { key1: ["val1", "val2"], key2: ["val3", "val4"] };
let joinedData = Object.values(obj).flat().join();
console.log(joinedData);
If you have some arrays that contain empty strings, then you may want to filter those out, with filter(Boolean)
:
let obj = { key1: ["val1", "val2"], key2: ["val3", "val4"], key3: [""], key4: [""] };
let joinedData = Object.values(obj).flat().filter(Boolean).join();
console.log(joinedData);
CodePudding user response:
You can use this - joinedData = Object.values(obj).flat().join(',')
CodePudding user response:
First join the both list in any single list like
var newlist = obj["key1"].join(obj["key2"]);
After join the values by comma seprated
joinedData = newlist.join(',');
CodePudding user response:
get all values from obj using let objValues = Object.values(obj);
now you can a for loop over obj values and append both elms like for(const v of objValues) { joinedData.push(v[0]); joinedData.push(v[1]); }
or nested for loop works too
let obj = {};
let joinedData = [];
obj["key1"] = ["val1", "val2"];
obj["key2"] = ["val3", "val4"];
let objValues = Object.values(obj); //List of tuples ?
for (const v of objValues) {
joinedData = v[0] ',';
joinedData = v[1] ' ';
}
console.log(joinedData)
CodePudding user response:
if you were to write out your object literally, you would have:
obj = {key1 : ["val1", "val2"], key2 : ["val3", "val4"]}
Array.join()
concatenates array elements into a string. Array elements that are arrays themselves cannot be directly concatenated into a string. Try:
let str = '';
for(let i of Object.values(obj)) { // retrieve each value (which is an array)
str = i.join(', ') ', '; // join elements of each array & concatenate
} // extra comma between each joined array
console.log(str)
You still need to strip the extra comma off the end