Create One string from elements in an Array of Objects - javascript

I am trying to create ONE string from an array of objects family and have them separated by commas except for the last element Mary
const family = [
{Person: {
name: John
}}, {Person: {
name: Mike
}}, {Person: {
name: Link
}}
, {Person: {
name: Mary
}}];
I want the string to be like this
"John, Mike, Link or Mary"
I tried using family.toString() but that gives me "John, Mike, Link, Mary" and doesn't allow me to replace "," with an "OR"

Use pop() to get (and remove) the last name. Then use join() to add the rest.
Thx to #charlietfl for suggesting a check on the number of names to prevent something like: and John.
const family = [
{ Person: { name: "John" } },
{ Person: { name: "Mike" } },
{ Person: { name: "Link" } },
{ Person: { name: "Mary" } }
];
// Get all the names
const names = family.map((x) => x.Person.name);
// Get result based on number of names
let result = '';
if (names.length === 1) {
// Just show the single name
result = names[0];
} else {
// Get last name
const lastName = names.pop();
// Create result
result = names.join(', ') + ' and ' + lastName;
}
// Show output
console.log(result);

I don't think there's a super-elogant option. Best bet is something like:
function joinWord(arr, sep, finalsep) {
return arr.slice(0,-1).join(sep) + finalsep + arr[arr.length-1];
}
and then
joinWord(family.map(x=>x.person.name), ', ', ' or ');
You could make the invocation a little nicer at the cost of performance and modularity with:
Array.prototype.joinWord = function joinWord(sep, finalsep) {
return this.slice(0,-1).join(sep) + finalsep + this[this.length-1];
}
family.map(x=>x.person.name).joinWord(', ', ' or ')
But this is only a good idea if this is going to come up a lot within your program and your program is never going to be a part of something bigger. It effects every array.

How about
let sp = ' or ';
family.map(x => x.Person.name)
.reduceRight(
(x,y) => {
const r = sp + y + x;
sp = ', ';
return r;
}, '')
.replace(', ', '');
Hope, this question was for the school homework :)

Related

Apply template string dynamically in JavaScript [duplicate]

I have a string with say: My Name is %NAME% and my age is %AGE%.
%XXX% are placeholders. We need to substitute values there from an object.
Object looks like: {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"}
I need to parse the object and replace the string with corresponding values. So that final output will be:
My Name is Mike and my age is 26.
The whole thing has to be done either using pure javascript or jquery.
The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys.
However, if you just had to do string interpolation, you can use:
const str = `My name is ${replacements.name} and my age is ${replacements.age}.`
Note the backticks delimiting the string, they are required.
For an answer suiting the particular OP's requirement, you could use String.prototype.replace() for the replacements.
The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).
var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"},
str = 'My Name is %NAME% and my age is %AGE%.';
str = str.replace(/%\w+%/g, function(all) {
return replacements[all] || all;
});
jsFiddle.
If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the in operator to achieve this.
jsFiddle.
However, if your format doesn't have a special format, i.e. any string, and your replacements object doesn't have a null prototype, use Object.prototype.hasOwnProperty(), unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype.
jsFiddle.
Otherwise, if your replacement string was 'hasOwnProperty', you would get a resultant messed up string.
jsFiddle.
As a side note, you should be called replacements an Object, not an Array.
How about using ES6 template literals?
var a = "cat";
var b = "fat";
console.log(`my ${a} is ${b}`); //notice back-ticked string
More about template literals...
Currently there is still no native solution in Javascript for this behavior. Tagged templates are something related, but don't solve it.
Here there is a refactor of alex's solution with an object for replacements.
The solution uses arrow functions and a similar syntax for the placeholders as the native Javascript interpolation in template literals ({} instead of %%). Also there is no need to include delimiters (%) in the names of the replacements.
There are two flavors (three with the update): descriptive, reduced, elegant reduced with groups.
Descriptive solution:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(
/{\w+}/g,
placeholderWithDelimiters => {
const placeholderWithoutDelimiters = placeholderWithDelimiters.substring(
1,
placeholderWithDelimiters.length - 1,
);
const stringReplacement = replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters;
return stringReplacement;
},
);
console.log(string);
Reduced solution:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(/{\w+}/g, placeholder =>
replacements[placeholder.substring(1, placeholder.length - 1)] || placeholder
);
console.log(string);
UPDATE 2020-12-10
Elegant reduced solution with groups, as suggested by #Kade in the comments:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '26',
};
const string = stringWithPlaceholders.replace(
/{(\w+)}/g,
(placeholderWithDelimiters, placeholderWithoutDelimiters) =>
replacements[placeholderWithoutDelimiters] || placeholderWithDelimiters
);
console.log(string);
UPDATE 2021-01-21
Support empty string as a replacement, as suggested by #Jesper in the comments:
const stringWithPlaceholders = 'My Name is {name} and my age is {age}.';
const replacements = {
name: 'Mike',
age: '',
};
const string = stringWithPlaceholders.replace(
/{(\w+)}/g,
(placeholderWithDelimiters, placeholderWithoutDelimiters) =>
replacements.hasOwnProperty(placeholderWithoutDelimiters) ?
replacements[placeholderWithoutDelimiters] : placeholderWithDelimiters
);
console.log(string);
You can use JQuery(jquery.validate.js) to make it work easily.
$.validator.format("My name is {0}, I'm {1} years old",["Bob","23"]);
Or if you want to use just that feature you can define that function and just use it like
function format(source, params) {
$.each(params,function (i, n) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
})
return source;
}
alert(format("{0} is a {1}", ["Michael", "Guy"]));
credit to jquery.validate.js team
As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf().
Placeholders:
%s String.
%d,%i Integer number.
%f Floating point number.
%o Object hyperlink.
e.g.
console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);
BTW, to see the output:
In Chrome, use shortcut Ctrl + Shift + J or F12 to open developer tool.
In Firefox, use shortcut Ctrl + Shift + K or F12 to open developer tool.
#Update - nodejs support
Seems nodejs don't support %f, instead, could use %d in nodejs.
With %d number will be printed as floating number, not just integer.
Just use replace()
var values = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
var substitutedString = "My Name is %NAME% and my age is %AGE%.".replace("%NAME%", $values["%NAME%"]).replace("%AGE%", $values["%AGE%"]);
You can use a custom replace function like this:
var str = "My Name is %NAME% and my age is %AGE%.";
var replaceData = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
function substitute(str, data) {
var output = str.replace(/%[^%]+%/g, function(match) {
if (match in data) {
return(data[match]);
} else {
return("");
}
});
return(output);
}
var output = substitute(str, replaceData);
You can see it work here: http://jsfiddle.net/jfriend00/DyCwk/.
If you want to do something closer to console.log like replacing %s placeholders like in
>console.log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright")
>Hello Loreto how are you today is everything allright?
I wrote this
function log() {
var args = Array.prototype.slice.call(arguments);
var rep= args.slice(1, args.length);
var i=0;
var output = args[0].replace(/%s/g, function(match,idx) {
var subst=rep.slice(i, ++i);
return( subst );
});
return(output);
}
res=log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright");
document.getElementById("console").innerHTML=res;
<span id="console"/>
you will get
>log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright")
>"Hello Loreto how are you today is everything allright?"
UPDATE
I have added a simple variant as String.prototype useful when dealing with string transformations, here is it:
String.prototype.log = function() {
var args = Array.prototype.slice.call(arguments);
var rep= args.slice(0, args.length);
var i=0;
var output = this.replace(/%s|%d|%f|%#/g, function(match,idx) {
var subst=rep.slice(i, ++i);
return( subst );
});
return output;
}
In that case you will do
"Hello %s how are you %s is everything %s?".log("Loreto", "today", "allright")
"Hello Loreto how are you today is everything allright?"
Try this version here
This allows you to do exactly that
NPM: https://www.npmjs.com/package/stringinject
GitHub: https://github.com/tjcafferkey/stringinject
By doing the following:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
// My username is tjcafferkey on Git
I have written a code that lets you format string easily.
Use this function.
function format() {
if (arguments.length === 0) {
throw "No arguments";
}
const string = arguments[0];
const lst = string.split("{}");
if (lst.length !== arguments.length) {
throw "Placeholder format mismatched";
}
let string2 = "";
let off = 1;
for (let i = 0; i < lst.length; i++) {
if (off < arguments.length) {
string2 += lst[i] + arguments[off++]
} else {
string2 += lst[i]
}
}
return string2;
}
Example
format('My Name is {} and my age is {}', 'Mike', 26);
Output
My Name is Mike and my age is 26
Another solution if you're using node.js is StackExchange's own formatUnicorn utility function (https://www.npmjs.com/package/format-unicorn):
let x = {name:'jason', food:'pine cones'};
let s = '{name} enjoys a delicious bowl of {food}';
let formatted = x.formatUnicorn(s);
Also, a bit of an edge case, but if you aren't using Node but you do just happen to be writing a userscript for SE sites, then formatUnicorn will already be on the String prototype.
As a quick example:
var name = 'jack';
var age = 40;
console.log('%s is %d yrs old',name,age);
The output is:
jack is 40 yrs old
Here is another way of doing this by using es6 template literals dynamically at runtime.
const str = 'My name is ${name} and my age is ${age}.'
const obj = {name:'Simon', age:'33'}
const result = new Function('const {' + Object.keys(obj).join(',') + '} = this.obj;return `' + str + '`').call({obj})
document.body.innerHTML = result
const stringInject = (str = '', obj = {}) => {
let newStr = str;
Object.keys(obj).forEach((key) => {
let placeHolder = `#${key}#`;
if(newStr.includes(placeHolder)) {
newStr = newStr.replace(placeHolder, obj[key] || " ");
}
});
return newStr;
}
Input: stringInject("Hi #name#, How are you?", {name: "Ram"});
Output: "Hi Ram, How are you?"
ES6:
const strFormat = (str, ...args) => args.reduce((s, v) => s.replace('%s', v), str);
// Use it like:
const result = strFormat('%s is %s yrs old', 'name', 23);
Lots of good/similar answers here. I wanted the ability to easily get a nested key in an object (or perhaps some JSON data structure) for substitution, so I took the following simple approach:
const getKey = (d, path) => {
// path can be a string like 'key1.key2' or an iterable of keys
if (typeof(path) === 'string') {
path = path.split('.')
}
return path.reduce((x, y) => x[y], d)
}
const inject = (str, obj) => str.replace(/\${(.*?)}/g, (x,g)=> getKey(obj, g));
// Example
> const str = 'there are ${a} ways to ${b.c}'
undefined
> inject(str, {'a':'many', 'b': {'c': 'skin a cat'}})
'there are many ways to skin a cat'
Some inspiration from this and this.
This is a merged solution of Gerson Diniz and Shubham Vyas.
It is possible to pass a set of arguments or an object.
function strSwap(str) {
if (!str) return null;
let args = [];
for (let a of arguments)
args.push(a);
args.shift();
if (!args.length) return null;
// replacement by object - {{prop}}
if (!!(args[0].constructor && args[0].constructor.name.toLowerCase() === 'object')) {
for (let i in args[0]) {
let n = `{{${i}}}`;
str = str.includes(n) ? str.replaceAll(n, args[0][i] + '') : str;
}
}
// replacement by placeholders - %s
else {
str = args.reduce((s, v) => s.replace('%s', v), str);
}
return str;
}
// ---------------------
console.log(strSwap('Hello %s, my name is %s.', 'alice', 'bob'));
console.log(strSwap('Hello {{a}}, my name is {{b}}. Hello {{b}}.', {
a: 'alice',
b: 'bob'
}));

How to get inner array in javascript

I'm trying to get all the contents from an array.
This is the function that extracts the data for display via innerHTML:
window.location.href = 'gonative://contacts/getAll?callback=contacts_callback';
function contacts_callback(obj) {
var contactinfo = obj.contacts.map(({givenName}) => givenName) + " " +
obj.contacts.map(({familyName}) => familyName) + " " + " (" +
obj.contacts.map(({organizationName}) => organizationName) + ") " +
obj.contacts.map(({phoneNumbers.phoneNumber}) => phoneNumbers.phoneNumber) + "<br>";
document.getElementById("demo").innerHTML = contactinfo;
}
This is an example of what the input looks like when there are only 2 contacts:
{"success":true,"contacts":[
{
"emailAddresses":[],
"phoneNumbers":
[
{
"label":"unknown",
"phoneNumber":"XXX-XXXXXXX"
}
],
"givenName":"John",
"organizationName":"Apple",
"familyName":"Appleseed",
},
{
"emailAddresses":[],
"phoneNumbers":
[
{
"label":"unknown",
"phoneNumber":"XXX-XXXXXXX"
}
],
"givenName":"John",
"organizationName":"Apple",
"familyName":"Appleseed",
},
]
}
I just want the result to be listed as:
John Appleseed (Apple) XXX-XXXXXXX
John Appleseed (Apple) XXX-XXXXXXX
Two issues:
You are displaying all given names, then all family names, ...etc, each with a separate .map() call. Instead only perform one .map() call on the array and then display the properties for each iterated object.
phoneNumbers.phoneNumber is not a correct reference. phoneNumbers is an array, so you should iterate it.
Also:
Template literals make it maybe a bit easier to build the string
You can use .join("<br>") to glue the lines together with line breaks.
Here is a corrected version:
function contacts_callback(obj) {
var contactinfo = obj.contacts.map(o =>
`${o.givenName} ${o.familyName} (${o.organizationName}) ${
o.phoneNumbers.map(n => n.phoneNumber)
}`)
.join("<br>");
document.getElementById("demo").innerHTML = contactinfo;
}
// Demo
var obj = {"success":true,"contacts":[{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"John","organizationName":"Apple","familyName":"Appleseed",},{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"John","organizationName":"Apple","familyName":"Appleseed",},]};
contacts_callback(obj);
<div id="demo"></div>
It is hard to give an answer since is hard to tell what you can have in your phoneNumbers array and if you will also display one line for each phone number in that array.
I'll do something like this:
function contacts_callback(obj) {
let arrayContacts = [];
// Iterate over all your contacts
obj.contacts.forEach(item => {
// Iterate over each contact's phone numbers
item.phoneNumbers.forEach(phone => {
// Building your string with string interpolation and pushing to result array
// You could also add <br> or other tags needed here
arrayContacts.push(`${item.givenName} ${item.familyName} (${item.organizationName}) ${phone.phoneNumber}`);
});
});
// Return your array, use it in your innerHTNL, etc.
return arrayContacts;
}
If Your obj is called "obj", than:
const result = obj.contacts.map(contact =>{
return `${contact.givenName} ${contact.familyName} (${contact.organizationName}) ${contact.phoneNumbers[0].phoneNumber}`
}
this code will give back an array of informations that U asked, but if user has more than 1 phone number, it will take only first from the list

Bootstrap selectpicker val won't accept an object just string

I want to understand one behavior from selectpicker. I'm trying load this this element with one attribute from my session:
Template.checkNotification.onRendered(function () {
var currentNotification = Session.get("currentNotification");
this.$('#symptoms1').selectpicker({
multipleSeparator: ' ',
});
this.$('#symptoms2').selectpicker({
multipleSeparator: ' ',
});
var symptoms = [];
for (var symptom of currentNotification.symptom.symptoms) {
symptoms.push('"' + symptom.name + ';;' + symptom.value + '"');
}
var symptomsSelected = symptoms.join(", ");
var test1 = ['Dor de Cabeça;;dor-de-cabeca','Náusea;;nausea'];
var test2 = "["+symptomsSelected+"]";
this.$('#symptoms1').selectpicker('val', test1);
this.$('#symptoms2').selectpicker('val', test2);
});
When I execute this code, only the element #symptom1 works and loads the proper options into the selectpicker.
How can I build an array of option to provide to selectpicker?
If you want to pass the symptoms to the selectpicker, you need to provide it as a native array. This code builds the array the original way and the new way (suitable for assigning to the val):
var currentNotification = {
symptom: {
symptoms: [
{ name: "symptom1", value: "value1" },
{ name: "symptom2", value: "value2" },
{ name: "symptom3", value: "value3" },
{ name: "symptom4", value: "value4" },
{ name: "symptom5", value: "value5" }
]
}
};
var symptoms = [];
for (var symptom of currentNotification.symptom.symptoms) {
symptoms.push('"' + symptom.name + ';;' + symptom.value + '"');
}
var symptomsSelected = symptoms.join(", ");
var test1 = "["+symptomsSelected+"]";
var test2 = $.map(currentNotification.symptom.symptoms, function(symptom) {
return symptom.name + ';;' + symptom.value;
});
console.log("test1: ", typeof test1, " value: ", test1);
console.log("test2: ", typeof test2, " value: ", test2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
How does this work? The jQuery $.map function will process each of the symptoms from the currentNotification.symptom.symptoms array, and format them individually for use with selectpicker. Each element is formatted, but the array is left as a native Javascript array, with each element corresponding to the original currentNotification.symptom.symptoms array.
Compare the results of test1 and test2 to see the difference:
test1: string value: ["symptom1;;value1", "symptom2;;value2", "symptom3;;value3", "symptom4;;value4", "symptom5;;value5"]
test2: object value: [
"symptom1;;value1",
"symptom2;;value2",
"symptom3;;value3",
"symptom4;;value4",
"symptom5;;value5"
]
Note that in this example code, test1 is a string, which is formatted like an array. This resembles a JSON array value, not a native Javascript array value. test2 is a Javascript array suitable for use with selectpicker.
Using the $.map solution will solve your current problem and produce a proper Javascript array. Now, you can use this to set the val of the selectpicker:
this.$('#symptoms2').selectpicker('val', test2);
plunker: http://plnkr.co/edit/sjwK1e?p=preview
$scope.symptomsSelected="["+'"\My selected item is string\"'+"]"
$scope.test2 =angular.fromJson($scope.symptomsSelected);
$scope.test2=$scope.test2[0];
{{test2}}
<br>
{{symptomsSelected}}

Dynamically add link with String parameter

I have a REST backend link mywebsite/guests, which returns list of guests. In the front end, I want to display the guests as links. Here's the code
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(' + guest.id + ')">' + guest.name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
I should mention that guest.id is a string.
The console always print undefined. My question, how can I add these links with String parameters?
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(this)" data-id='+guest.id+'>' + guest.name + '</a><br>')
}
function showGuest(this) {
console.log($(this).data('id'))
}
The main issue is that you are trying to access the property of dynamically bound DOM elements in your showGuest(id) function. You should use the onClick function in the following way-
var guests = [{"id":1, "name":"John Doe"},
{"id":2, "name":"David Jones"}];
for(guest of guests) {
$('#guest_list').append('<a class="guest" data-id="'+guest.id+'">' + guest.name + '</a><br>');
}
$('#guest_list').on('click', 'a.guest', function() {
var id = $(this).attr('data-id');
$('.message').text('').append("Clicked guest with ID: "+id);
});
Working JSFiddle here - https://jsfiddle.net/2dkpsve8/
Hope this helps!
The way to approach this problem depends on the format and content of the guests variable. If you started with this object:
var guests = {
'123': {id: 123, name: 'joe'},
'234': {id: 234, name: 'jane'}
};
Then key would be "123" and "234" in the following loop, and the object values would be guests[key]:
for(var key in guests) {
$('#guest_list').append('<a onclick="showGuest(' + guests[key].id + ')">' + guests[key].name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
But if you're already using jQuery, take a look at jQuery.each for another looping option.
On the other hand, if guests is an array, as in:
var guests = [
{id:"123", name:"joe"},
{id:"234", name:"jane"}
];
then you will just want to use something like:
for(var i=0; i < guests.length; i++) {
// id is guests[i].id
// name is guests[i].name
}
Amazingly,
$('#guest_list').append('<a onclick="showGuest(' + "guest.id" + ')">' + guest.name + '</a><br>')
works fine! I don't know way. "guest.id" is replaced by the actual id of guest.

I don't understand this function. [Codecademy Contact List excercise]

So the "for var x in friends" loop is going to search each key inside friends, which would be bill and steve, and then with "friends[x].firstName === name" we are checking if the first name is equal to "name", but how does the program know if "name" is Steve or Bill? I'm missing something here.
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: " ",
address: [' ', ' ', ' ',' ']
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: " ",
address: [' ', ' ', ' ',' ']
}
};
var list = function(friends) {
for (var x in friends) {
console.log(x);
}
};
var search = function(name) {
for (var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
for (var x in friends)
This iteates over all keys in friends, resulting in two loop iterations with
x = "bill"
x = "steve"
Then with friends[x] in the loop you access friends.bill and freinds.steve.
The name variable is given as a parameter to search(name). This effectivly searches all entries in the dict friends for firstName == name.
here we have defined search as a function search which accepts an argument name .
var search = function(name)
and we use the function like
search('Bill')
So the function knows which name we are looking for, which is Bill . It will iterate through each item and compare each firstName with Bill. It returns the corresponding friends[x] , when it finds a match .
The advantage of function with parameter is that, with the same function we can search for any name . ex : search('Steve') , search('Bill') .
if you don't understand functions with parameters, revisit the codeacademy section understanding parameters - js

Categories