I've an array which has objects inside it:
[
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
]
I would like to join all the strings i.e pointName like this : "One-Two-Three"
Any help is appreciated. Thanks.
Edit 1:
This is what I tried so Far:
this.viaPoints.forEach(x=> {
var splitted = x.pointName.split(" ");
console.log('I5: ',splitted[0].join("-"));
});
The reason I've split is because the string will have extra characters some times like "One - A". So I've used split to remove the extra
Edit 2: In my case this helped as I mentioned above that to remove extra characters and strings:
var permittedValues1 = this.viaPoints.map(value => value.pointName.split(" ")[0]).join("-") ;
CodePudding user response:
You can use Array.prototype.reduce
function to return an array which contains pointName
for each object in the array and join all value of the return array with -
.
let data = [
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
]
let result = data.reduce((accumulator, current) => {
return accumulator.concat(current.pointName);
}, []).join('-');
console.log(result);
CodePudding user response:
You can use .map
and .join
functionalities too. Here .map
will take the values based upon the key-pointName and .join
is used to return an array as a string. The elements will be separated by a specified separator (here "-").
let array = [
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
];
var permittedValues = array.map(value => value.pointName).join("-") ;