Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate object property values

I have a JavaScript object. I would like to concatenate all its property values, say:

tagsArray["1"] = "one";
tagsArray["2"] = "two";
tagsArray["Z"] = "zed";

result = "one,two,zed"

Just for background, I have several checkboxes, and I need to update a hidden selectedKeys field. Example of server side (Asp.Net) code + AngularJS

<input hidden id="selectedKeys" value="1,5,8">

@foreach (var tag in tagsDictionary) {
    <input type="checkbox" 
        ng-model="tagsArray['@tag.Key']" 
        ng-true-value  ="'@tag.Key'" 
        ng-false-value ="" 
        ng-change="change(tagsArray)" />@tag.Value
}

so on each change I need to update the #selectedKeys value

like image 875
serge Avatar asked Jul 25 '17 17:07

serge


2 Answers

You can try this way also,

var tagsArray = {};
var result;
tagsArray["1"] = "one";
tagsArray["2"] = "two";
tagsArray["Z"] = "zed";

result = Object.keys(tagsArray).map(function(k){return tagsArray[k]}).join(",");
alert(result);
like image 33
Always Sunny Avatar answered Oct 12 '22 22:10

Always Sunny


One possible approach:

var tagsArray = {};
tagsArray["1"] = "one";
tagsArray["2"] = "two";
tagsArray["Z"] = "zed";

var result = Object.values(tagsArray).join(",");
console.log(result); // "one,two,zed"

More on Array.prototype.join and Object.values.

like image 161
TimoStaudinger Avatar answered Oct 12 '22 22:10

TimoStaudinger