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)});
});
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!
So there is an array of object called employees that has employee's credentials.
I am supposed to delete the object if the employee's name is Theo, and if the employee's name is Lorie I should change the department's property to 'HR'
I've tried using a for loop to go through the objects in the array and change their properties. but it would not return the iterated array.
maybe I need to use the .reduce() method
Here is the code I've tried
It should be working!
Your array of objects.
var employees = [
{
"firstName": 'Von',
"lastName": 'budibent',
"email": "email#mail.com",
"departement": "Sales"
},
{
"firstName": 'Theo',
"lastName": 'Trill',
"email": "email#mail.com",
"departement": "Services"
},
{
"firstName": 'Lorie',
"lastName": 'Trill',
"email": "email#mail.com",
"departement": "Research and Development"
}
];
Then you need to filter by firstName and then mapping the data.
var adjustedEmployees = employees
.filter(employee => employee.firstName !== 'Theo')
.map((employee) => {
if (employee.firstName === 'Lorie') employee.departement = 'HR';
return employee;
});
//I needed to use a function with no parameters, I figured out how to do it.
Solved question
//Remove employe with firstname 'Theo'
var result = employees.filter(employee => employee.firstName !== 'Theo');
//Change department of Lorie to 'HR'
result.forEach(el => {
el.departement = el.firstName === 'Lorie' ? 'HR' : el.departement
})
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.
I'm parsing a JSON message which looks something like:
{
staff : [
{name : 'John', department : 'Math'},
{name : 'Sally', department : 'Science'},
],
students : [
{name : 'Bob', department : 'Law'},
{name : 'Lisa', department : 'IT'}
]
}
From which I'd like to pull out an array of each separate value.
i.e.
names -> ['John', 'Sally', 'Bob', 'Lisa']
At the moment I'm doing something like
var names = [];
msg.staff.forEach(function(e) { names.push(e.name) })
msg.students.forEach(function(e) { names.push(e.name)})
This feels overly verbose, just wondering if there's a cleaner way to approach this (for every attribute). I'm already including lodash in this project.
You can use _.pluck to get the value of a property of each object in an array:
_.pluck(obj.staff.concat(obj.students), 'name')
Your instinct is right; you don't need a mutable array to do this with lodash.
_(obj).map().flatten().pluck('name').value();
This version works for any number of array values in o.
JSBin
Edit missed that you had lodash available, will leave this vanilla JS version here anyway.
You could use map to be more concise:
var directory = {
staff : [
{name : 'John', department : 'Math'},
{name : 'Sally', department : 'Science'},
],
students : [
{name : 'Bob', department : 'Law'},
{name : 'Lisa', department : 'IT'}
]
};
var names = directory.staff.concat(directory.students).map(function(person) {
return person.name;
});
If you don't know the individual key names before hand, you could do:
Object.keys(directory).map(function(key) {
return directory[key]
}).reduce(function(p,c){
return p.concat(c)
}).map(function(person) {
return person.name;
});
I didn't catch the requirement of getting an array of all values stored under each key, this should do it though:
Object.keys(directory).map(function(key) {
return directory[key];
}).reduce(function(p,c) {
return p.concat(c);
}).reduce(function(p, c) {
Object.keys(c).forEach(function(oKey) {
if(p[oKey]) p[oKey].push(c[oKey]);
else p[oKey] = [c[oKey]];
});
return p;
}, {});
This returns the following:
{
"name":["John","Sally","Bob","Lisa"],
"department": ["Math","Science","Law","IT"]
}
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));