Ster32
Ster32

Reputation: 415

Replace the comma with semicolon in array

I have this object I have an object with an array with different values

var myObj = {
            "number": 10,
            "general": "general",
            "array": [{
                "num1": 11,
                "text": "text1",
            }, {
                "num2": 1,
                "text": "text2",
            }, {
                "num3": 3,
                "text": "text3",

            } ]
        };

I take back the result text1,text2,text3 using this

var result = myObj.array.map(function (item) {
  return item.text;
});

How can I take back this result text1;text2;text3

Upvotes: 1

Views: 6814

Answers (2)

user663031
user663031

Reputation:

Join them with join:

var result = myObj.array.map(function (item) {
    return item.text;
}).join(';');

Upvotes: 3

Dal Hundal
Dal Hundal

Reputation: 3324

At the moment, you're not really getting them with commas - that's just how your console is displaying an array of values. To return what you want (the items delimited by a semicolon, just use the Array.join function.

var result = myObj.array.map(function (item) {
  return item.text;
}).join(";");

From MDN;

The join() method joins all elements of an array into a string.

Syntax

str = arr.join([separator = ','])

Parameters

separator - Optional. Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma. If separator is an empty string, all elements are joined without any characters in between them.

Upvotes: 7

Related Questions