Substitute string with placeholder values coming from JSON object - javascript

I have a string "Good $timeOfTheDay$, $name$"
$timeOfTheDay$ and $name$ are placeholders whose values are contained in a JSON object.
var content = { "timeOfTheDay" : "evening",
"name" : "Jack",
"city" : "New York",
"age" : "25",
}
Want to substitute the placeholders in the string with the values from the JSON object. The resulting string would be: "Good evening, Jack"
Want to do this in javascript. This does not involve any interaction with the DOM.
I'm guessing the brute force way to do it would be via writing JS code to do the replace but is there a library or another way to do this?
Appreciate any ideas/help. Thanks!

The extended solution using String.split, String.replace, Array.map and Array.join functions:
var content = {"timeOfTheDay" : "evening", "name" : "Jack", "city" : "New York", "age" : "25"},
str = "Good $timeOfTheDay$, $name$", replaced = "";
var parts = str.split(/(\$\w+?\$)/g).map(function(v) {
replaced = v.replace(/\$/g,"");
return content[replaced] || replaced;
});
console.log(parts.join("")); // "Good evening, Jack"
Additional example:
...
str = "$name$ lives in $city$. He is $age$";
...
console.log(parts.join("")); // "Jack lives in New York. He is 25"

Just use String.prototype.replace function
var content = { "timeOfTheDay": "evening", "name": "Jack", "city": "New York", "age": "25", }
var str = "Good $timeOfTheDay$, $name$"
var result = str.replace('$timeOfTheDay$', content.timeOfTheDay)
.replace('$name$', content.name);
document.write(result);

var content = { "timeOfTheDay" : "evening",
"name" : "Jack",
"city" : "New York",
"age" : "25",
}
document.getElementById('greeting').placeholder = 'Good ' + content.timeOfTheDay + ', ' +content.name;
<input id='greeting'>

This library can be useful for replacing placeholder. This could also be used to recursively replace placeholders.
https://github.com/tarangkhandelwal/substitutor.js
Ex:
nameJson= {
"first":"John",
"last":"Doe"
}
var fullName = substitutor('My name is {first} {last} ', nameJson);

If you want to use ${var} convension:
var content = {
timeOfTheDay: 'evening',
name: 'Jack',
city: 'New York',
age: '25'
};
var str = 'Good ${timeOfTheDay}, ${name}. I am from ${city}, ${age} years old';
var parts = str.split(/(\$\{\w+?})/g).map(function(v) {
var replaced = v.replace(/\$\{(\w+?)}/g, '$1');
return content[replaced] || v;
});
console.log(parts.join(''));
Output
Good evening, Jack. I am from New York, 25 years old

Related

How to convert a set of strings into 'ONE' array in JavaScript?

I have some data in a form of string and I want them to be inside an array so I can filter them.
I've tried .split() but it created individual arrays NOT one array with all the data inside it.
This is how the part of data looks.
"Jane Doe"
"John Smith"
"Rose Benet"
list goes on
What is the best way to convert these strings into one array?
Here's what I've tried.
for (let i = 0; i < customerData.length; i++) {
let arrays = customerData[i].name;
function flatten(arr) {
return [].concat(...arr);
}
console.log(flatten(arrays));
}
And the result was rather than adding all strings nicely into one array, it gave each string its own array like this.
Array(14)
0: "J"
1: "a"
2: "n"
3: "e"
4: " "
5: "D"
6: "o"
7: "e"
length: 8
Array(11)
0: "J"
1: "o"
2: "h"
3: "n"
4: " "
5: "S"
6: "m"
7: "i"
8: "t"
9: "h"
length: 10
list goes on
The desirable result would be:
['Jane Doe', 'John Smith', "Rose Benet" list goes on]
This is how 'CustomerData' is defined:
CustomerData = [
{
"index": 0,
"name" : "A",
"gender" : "male",
"company" : "CC"
},
{
"index": 1,
"name" : "B",
"gender" : "female",
"company" : "DD"
}]
Here's what I have tried so far. In my React app, I want to make a search box so users can put in search term than filtered result will be displayed.
This is the React code.
state = {
names: [],
searchTerm: ''
}
editSearchTerm = (e) => {
this.setState({ searchTerm: e.target.value });
}
dynamicSearch = () => {
for(let i = 0; i < customerData.length; i++) {
this.setState({ names: customerData[i].name });
}
return this.state.names.filter(name =>
name.toLowerCase().includes(this.state.searchTerm.toLocaleLowerCase()))
}
And when I try to type in some search term, React throws an error "TypeError: this.state.names.filter is not a function".
I assume the error msg means 'name' property should be an array. When I inspect in Chrome dev tool, 'customerData[i].name' returns as strings.
This is where I got stuck. I can't seem to get "name" values inside an array.
They either get into an array of their own, (so rather than Array(63), it shows Array(1), Array(1), Array(1)......in console.)
How can I convert 'customerData[i].name' into one array?
Or if you have the names in one variable, for instance:
const names = "Alex Kyle Aaron";
You can do:
const arrayOfNames = names.split(" ");
console.log(arrayOfNames); // ["Alex", "Kyle", "Aaron"]
Hope that helped! Good luck.
Just do this:
const arr = ["Jane Doe", "John Smith", "Rose Banet"]
Javascript can simply create an array with [] and of course you can put data into there delimiting with several commas.
Would this help?
var data = `
Test Name
Pizza Cheese
Hello World
`;
console.log(data.split('\n').filter(n => n != ''));
let stringValue='Jane Doe John Smith Rose Benet';
let stringList = stringValue.split(' ');
let resultList=[];
stringList.forEach((item,index)=> { if(index%2){ resultList.push(stringList[index-1]+' '+item); } });
console.log(resultList);
resultList => ["Jane Doe", "John Smith", "Rose Benet"]
Given the structure of customerData you can get an array containing the "name" property of every object in customerData simply with:
customerData.map(customer => customer.name);
In action:
let customerData = [
{
"index": 0,
"name" : "A",
"gender" : "male",
"company" : "CC"
},
{
"index": 0,
"name" : "B",
"gender" : "female",
"company" : "DD"
}];
console.log(customerData.map(customer => customer.name));

Javascript How to find a complete class object in an array

I have an array of objects that I use for a materials table datasource. I need to see if this row already exists in the datasource array before adding it.
There is no key value in this array. So I need to check if all items are unique
var datasource = [
{ Name: Jon, Address: 123 something }, {Name: Tyler , Address: 333 Something}
]
var rowtoAdd = [
{ Name: Jon, Address: 123 something }
]
const found = datasource.find(x => x.name == rowtoAdd.Name && x.Address == rowtoAdd.Address)
Is there a better way?
One way you can do this is by hashing the elements. Your current solution takes O(n) time each time you need to check. if you create a hashtable it will take 0(n) to create the table but the run time will O(1) for all consecutive run.
var datasource = [
{ "Name": "Jon", "Address": "123 something" }, {"Name": "Tyler" , "Address": "333 Something"}
]
var map = datasource.reduce(function(map, obj) {
map[obj.Name+obj.Address] = true;
return map;
}, {});
rowtoAdd = { "Name": "Jon", "Address": "123 something" }
if(!map[rowtoAdd.Name+rowtoAdd.Address])
datasource.push(rowtoAdd)
So, in sort reduce your array to a hashmap

How to make an array of objects with different label and value in Reactjs

I am using this.state.student in react to display (name,school,class.etc)..
how i change the "school" display to "college" without replacing the value of "School" in the api..
as i am new to code i tried
'var student = [ {"name", "school", "class"}];'
'student[1] = "college";'
but this just replaces the value. i just want to change the display
of "school" please help
Check my code. I created a function addToArray that will accept a parameter of object then it will add it to the students array. This will give you an output of [{ name: "John Doe", school: "College", class: "A" }]
let students = [];
addToArray = student => {
students.push({
name: student.name,
school: student.school,
class: student.class
});
console.log(students);
};
this.addToArray({
name: "John Doe",
school: "College",
class: "A"
});
Use this to create an array of objects with different key and value pair,
var productArr = [];
productId = 1;
productName = 'Product Name';
productArr.push({ id: productId, name: productName });
Hope it'll work for you. Waiting for your response. Thank you!
You can try this:
var student = [ {"name": "school", "class":"XYZ"}];
student = [...student,{"name":"college","class":"ABC"}]
console.log(student)

convert flat json object into hierarchical xml

I have json object like this:
var client = {
"id": 1,
"name": "John Doe",
"name2": "Jane Doe",
"email": "John#test.com",
"phone": "+1-306-5555555",
"phoneType": "Home",
"phone2": "+1-306-5556666",
"phone2Type": "Business",
"gender": "Male",
"address": "1000 Center AVE",
"postCode": "S7J 1P3",
"city": "Saskatoon",
"province": "SK",
"country": "CA",
"dob": "1990-12-11T02:00:00.000Z",
"maritalStatus": "Single",
"occupation": "Software Developer",
"createdAt": "2015-12-07T08:14:21.000Z",
"updatedAt": "2016-01-19T13:35:10.000Z"
};
Which I want to convert into XML, this isn't a problem I know there great library like x2js that can do that for me.
My problem is xml file, need to follow a standard like this:
<GeneralPartyInfo>
<NameInfo>
<PersonName>
<Surname>Doe </Surname>
<GivenName>John</GivenName>
</PersonName>
<SupplementaryNameInfo>
<SupplementaryName>Jane Doe</SupplementaryName>
</SupplementaryNameInfo>
</NameInfo>
<Addr>
<DetailAddr>
<StreetName>Centre</StreetName>
<StreetNumber>1000</StreetNumber>
<csio:StreetTypeCd>AVE</csio:StreetTypeCd>
</DetailAddr>
<City>Saskatoon</City>
<StateProvCd>SK</StateProvCd>
<PostalCode>S7J 1P3</PostalCode>
<CountryCd>CA</CountryCd>
</Addr>
<Communications>
<PhoneInfo>
<PhoneTypeCd>Phone</PhoneTypeCd>
<CommunicationUseCd>Home</CommunicationUseCd>
<PhoneNumber>+1-306-5555555</PhoneNumber>
</PhoneInfo>
<PhoneInfo>
<PhoneTypeCd>Phone</PhoneTypeCd>
<CommunicationUseCd>Business</CommunicationUseCd>
<PhoneNumber>+1-306-5556666</PhoneNumber>
</PhoneInfo>
</Communications>
you can xml is nested while my json isn't, not mention name need to spliced to firstName and lastName and be inside PersonName which is child of NameInfo, and GeneralPartyInfo be the root parent (same thing for the address).
there two problems I have, the first one is a missing tags for example firstname is inside PersonName which inside NameInfo which inside GeneralPartyInfo and I can't do this
var firstName = client.name.split(' ').slice(0, -1).join(' ');
var lastName = client.name.split(' ').slice(-1).join(' ');
delete client.name;
client.PersonName.push({
GiveName: firstName,
Surname: lastName,
});
because JSON is an object not an array, it requires for me to convert JSON into an array (which is not recommended by other professionals here in SO), or I can save each one (Name, address, communication) into it separate json object then concat all of them together abdthe only way I found in SO to add parent json object was like this
var obj = {fistName: client.name.split(' ').slice(0, -1).join(' '), lastName: client.name.split(' ').slice(-1).join(' ');};
var obj2 = { "PersonName" : obj };
var obj3 = { "NameInfo" : obj2 };
my second problem is find a way to replace keys for example I want to replace postcode to PostalCode or phoneType to CommunicationUseCd
or just do it this way
var xml = "<GeneralPartyInfo><NameInfo><PersonName>
<Surname>" + client.name.split(' ').slice(0, -1).join(' '); + "</Surname>
<GivenName>"+client.name.split(' ').slice(-1).join(' ')+"</GivenName>"
but this solution is tedious, not efficient and doesn't look pretty and I'm looking more for stability and cleanliness of code.
For example How can I manipulate a json object to add parent to selected elements then I can replace keys through list that have keys to be replaced for example.
var translationObj = {
"firstName": "GivenName",
"lastName": "PersonName",
}
PS: I have lodash/underscore installed so a solution using underscore would be great.

parsing a JSON document without childnodes returns undefined

A webservice returns this JSON below
[
{
"companyuserId": "2",
"name": "mike jones",
"superiorname": null,
"departmentId": "26",
"departmentname": "Design",
"companyId": "06",
"UDID": "8df912053a16ab2b4c66a",
"isActive": "1",
"devicetoken": "e8a4c1fad76b45d918f6745bfe60d32a81504",
"email": "mike#yahoo.co.uk",
"phone": "5456465465654"
}
]
Thought it would be straight forward
name = data.name;
phone = data.phone;
email = data.email;
departmentname = data.departmentname;
companyId = data.companyId;
But I'm getting undefined, How else can I do this? I think maybe the data maybe in string format because when I alert data I get the result as pasted above rather than object: Object
That is an array of Objects.. And the Object is the First item inside an array.. So you need to use the index to access the object inside it..
So instead of name = data.name; try this name = data[0].name;
name = data[0].name;
phone = data[0].phone;
email = data[0].email;
departmentname = data[0].departmentname;
companyId = data[0].companyId;
Your JSON object is an array of objects, so it has to be accessed with fully qualified name.
Try this:
name = data[0].name;
phone = data[0].phone;
email = data[0].email;
departmentname = data[0].departmentname;
companyId = data[0].companyId;

Categories