This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I create Javascript array(JSON format) dynamically?
I am attempting to create the following:
var employees = {"accounting": [ // accounting is an array in employees.
{ "firstName" : "John", // First element
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary", // Second Element
"lastName" : "Smith",
"age" : 32 }
] // End "accounting" array.
} // End Employees
I started out with:
var employees=new Array();
How do I continue to append to the array dynamically (might change firstName with variable)?
var employees = {accounting: []};
employees.accounting.push({
"firstName" : "New",
"lastName" : "Employee",
"age" : 18
});
employees.accounting.push({ "firstName" : "New", // First element
"lastName" : "Person",
"age" : 55 });
var urNewFirstName='new john';
employees.accounting[0].firstName = urNewFistName;
function Employee(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
var employees = {};
employees.accounting = [];
employees.accounting.push(new Employee('John', 'Doe', 23));
employees.accounting.push(new Employee('Mary', 'Smith', 32));
Related
I'm trying to learn about prototypes and I tried to "re-define" console.log() so it's easier to use and write. Here's the code I used for it :
Object.prototype.cl = function() {
console.log(this.valueOf())
}
Then, I defined a table filled with objects :
let arr = [
{firstName : "John", lastName : "Doe", eyesColor : "Blue"},
{firstName : "Johnny", lastName : "Smith", eyesColor : "Brown"},
{firstName : "Janet", lastName : "Williams", eyesColor : "Green"},
]
Finally, I tried to log the values of the second line along with their names :
for(k in arr[1]) {
(k + " : " + arr[1][k]).cl()
}
Here's what I expected to see in the console :
firstName : Johnny
lastName : Smith
eyesColor : Brown
But for some reasons, after what's just above, it also showed this :
cl : function() {
console.log(this.valueOf())
}
Even if it's not defined at all in the array...
I saw that this function is defined as the same time of the object in the proto property but I don't know why it shows like this...
Can anyone enlighten me?
Thank you in advance!
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 3 years ago.
I'm trying to extract some of the fields from a Json response and push them into a Javascript array. I want the selection of the fields to be configurable. Here is what I'm doing:
Consider this as my JSON string:
{
"id" : "1234",
"orderNumber" : "1196",
"createdOn" : "2019-07-02T12:03:39.697Z",
"modifiedOn" : "2019-07-02T12:25:52.126Z",
"testmode" : false,
"customerEmail" : "a#b.com",
"billingAddress" : {
"firstName" : "John",
"lastName" : "Doe",
"address1" : "Wall Street",
"address2" : null,
"city" : "NYC",
"state" : "NY",
"countryCode" : "US",
"postalCode" : "12345",
"phone" : "1122334455"
}
}
Say I want to extract some of the fields (defined in the FIELDS variable) and push them in an array.
# NOTE: the variable `data` here is my json object
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']
var lineItem = []
# parse the data (my Json object)
for (var i = 0; i < FIELDS.length; i++){
lineItem.push(data[FIELDS[i]])
}
So, this seems to be working OK for the first level (the id, orderNumber and customerEmail) but not for the billingAddress.firstname, etc. This is what I'm wondering about.
My intent is to be able to modify the definition in the FIELDS variable without needing to make any change to the logic in the code.
Hope this makes sense.
Thanks!
As long as there are no periods in the key names this will work.
var data = {
"id" : "1234",
"orderNumber" : "1196",
"createdOn" : "2019-07-02T12:03:39.697Z",
"modifiedOn" : "2019-07-02T12:25:52.126Z",
"testmode" : false,
"customerEmail" : "a#b.com",
"billingAddress" : {
"firstName" : "John",
"lastName" : "Doe",
"address1" : "Wall Street",
"address2" : null,
"city" : "NYC",
"state" : "NY",
"countryCode" : "US",
"postalCode" : "12345",
"phone" : "1122334455"
}
};
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName'];
var lineItem = [];
for (var i = 0; i < FIELDS.length; i++){
let obj = data;
let parts = FIELDS[i].split(".");
while(parts.length) obj = obj[parts.shift()];
lineItem.push(obj)
}
console.log(lineItem);
You just need a function that will split that path on . and traverse the JSON data. With that you can just map() over your fields.
let data = {"id" : "1234","orderNumber" : "1196","createdOn" : "2019-07-02T12:03:39.697Z","modifiedOn" : "2019-07-02T12:25:52.126Z","testmode" : false,"customerEmail" : "a#b.com","billingAddress" : {"firstName" : "John","lastName" : "Doe","address1" : "Wall Street","address2" : null,"city" : "NYC","state" : "NY","countryCode" : "US","postalCode" : "12345","phone" : "1122334455"}}
var FIELDS = ['id', 'orderNumber', 'customerEmail', 'billingAddress.firstName', 'billingAddress.lastName']
// split an traverse
const getFromPath = (path, data) => path.split('.')
.reduce((curr, p) => curr && curr[p], data) // check for curr incase path is undefined
console.log(FIELDS.map(p => getFromPath(p, data)))
The function getFromPath will return undefined if any part of the traversal is not found in the object.
Suppose I have several nested objects(human1, human2, human3) in "human" object.
human: {
"human1": {
"name" : "John",
"sex" : "male",
"age" : 18
}
"human2": {
"name" : "Peter",
"sex" : "male",
"age" : 16
}
"human3": {
"name" : "May",
"sex" : "female",
"age" : 19
}
}
And I have another object called currentPlayer below, which I want it to be a vessel, in order to access the data from "human1", "human2", or "human3" for different use.
currentPlayer: {
"name" : "default",
"sex" : "default",
"age" : 0
}
Example: today I want currentPlayer to be John, and it goes
currentPlayer: {
"name" : "John",
"sex" : "male",
"age" : 18
}
And then I want currentPlayer to be Peter, and it goes:
currentPlayer: {
"name" : "Peter",
"sex" : "male",
"age" : 16
}
How do I iterate property values of currentPlayer like this with loop, not just key in one by one? Thanks...
Bellow code will iterate through all Properties of human object
listofhuman = Object.getOwnPropertyNames(human);
var currentPlayer;
for (var objHumanName in listofhuman) {
if (listofhuman[objHumanName].Name === "Jonh") {
currentPlayer = Object.create(listofhuman[objHumanName]);
break;
}
}
at the end of this loop you will get human which you wonted
if you do Object.getOwnPropertyNames(currentPlayer) this will return array of string which are the actual keys in object currentPlayer, and you can access those values by currentPlayer[arryofProp[0]]
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
This is my first time using lodash and I'm trying to figure out how to update each record within a JSON object. For example, let's say I have a person object:
"person":[
{
"firstName" : "Alex",
"lastName" : "Smith"
},
{
"firstName" : "Madison",
"lastName" : "Matthews"
}
]
I would like to add a new field called "fullName" to each record in person that is a combination of their first and last names. Is there a way I can do this using lodash and/or javascript? I don't want to use any other tool.
Thanks!
Here if you have persons collection(Array of json objects) then you can add one more property by traversing the collection with lodash function. There are other several ways also.
var persons = [
{
"firstName" : "Alex",
"lastName" : "Smith"
},
{
"firstName" : "Madison",
"lastName" : "Matthews"
}
];
var personsWithFullName = _(persons).forEach(function(person) {
person.fullName = person.firstName + person.lastName;
return person;
});
or
var newPersonsWithFullName = _.map(persons , function(person) {
return _.assign({}, person, {fullName: (person.firstName + person.lastName)});
});