Pick values of given properties from object into array - javascript

I have an object:
person = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
}
I have an array of key names in given order:
keys = ["occupation", "last_name", "city"]
I want to get this array:
["Doctor", "Doe", "Boston"]
It is important, that the answer should guarantee the order (JavaScript does not guarantee the order for object iteration).
I think there is probably some utility function in lodash/underscore to do it simply, but can't figure out any.

You can use Array.prototype.map for this. Map loops through an array and creates a new array by applying a function to each item. When you use the keys array as a starting point, and return the value in o for that key, you'll get a new array with only values.
When using "dynamic" key names, you use a object[stringKeyName] notation to retrieve a value.
var o = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
};
var keys = ["occupation", "last_name", "city"];
var result = keys.map(function(k) { return o[k]; });
console.log(result);
If it fits your style, you can create a helper method to replace the anonymous function:
var o = { birth_year: 1970, first_name: "John", last_name: "Doe", occupation: "Doctor", city: "Boston", married: true };
var keys = ["occupation", "last_name", "city"];
var prop = obj => key => obj[key];
var result = keys.map(prop(o));
console.log(result);

With Lodash you could use pick and values
var o = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
}
var keys = ["occupation", "last_name", "city"];
var result = _.values(_.pick(o, keys));
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Related

Create New Object key value pair base on array value

I need to generate csv for my client data but I need to include all headers came from my models.
The problem is some of my old client data has no existing fields. I want to create a new object with all the headers as a key and leave some empty string if a client has no data or no existing fields. Thanks for helping!
Here example of headers as key
let header = ["firstname", "lastname", "age", "gender", "address"];
Example for client info
let userInfo = [
{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
},
{
firstname: "Jane",
lastname: "Doe",
},
];
Expected Output
let userInfo = [
{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
address: "",
},
{
firstname: "Jane",
lastname: "Doe",
age: "",
gender: "",
address: "",
},
];
you can create an empty object with array.reduce
const emptyObj = header.reduce((acc, key) => {
acc[key] = "";
return acc;
}, {});
and use array.map on userInfo to return an object that concat the empty object with the one with value
let header = ["firstname", "lastname", "age", "gender", "address"];
let userInfo = [{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
},
{
firstname: "Jane",
lastname: "Doe",
},
];
const emptyObj = header.reduce((acc, key) => {
acc[key] = "";
return acc;
}, {});
const result = userInfo.map(user => {
return {
...emptyObj,
...user
};
})
console.log(result);

Compare typescript objects and add diff to new object

Within my Angular application, I need to compare two typescript objects and create a new object that consists of key/value pairs where the value of the key is different in the second object.
Here is my code:
const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};
let newObj = {};
for(let key in objBefore) {
if (objBefore[key] !== objAfter[key]) {
let newEntry = { key: objAfter[key]}
Object.assign(newObj, newEntry)
}
}
console.log(newObj)
The output is:
{ key: 'Johnson' }
I need the output to be:
{ firstName: "John", lastName: "Johnson" }
How do I assign the value of the key (e.g., firstName) instead of the variable (key)?
Just use square brackets on [key]
const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};
let newObj = {};
for(let key in objBefore) {
if (objBefore[key] !== objAfter[key]) {
let newEntry = { [key]: objAfter[key]}
Object.assign(newObj, newEntry)
}
}

Get accessed to plucked object using javascript and lodash

I have an array of users in my javascript. For each user I am comparing if that user appears in another list.
var users = USERS.getUsers();
for (var i = 0; i < users.length; i++) {
var u = users[i];
if (util.pluck(myList.adminUsers, 'email').includes(u.email)) {
// How do I check the value of the plucked value for myList.adminUsers.locationId ?
u.status = "admin";
}
}
users is an array of user objects.
[{...}]
0:
id: "1"
email: "johndoe#gmail.com"
firstname: "John"
lastname: "Doe"
roleid: "1"
_proto__: Object
1:
id: "2"
email: "janedoe#gmail.com"
firstname: "Jane"
lastname: "Doe"
roleid: "1"
_proto__: Object
myList.adminUsers is also an array of user objects but also with locationId.
[{...}]
0:
id: "1"
email: "johndoe#gmail.com"
firstname: "John"
lastname: "Doe"
roleid: "1"
locationId: "123"
_proto__: Object
I need to compare another field in this check. So I need to see if the plucked object from myList.adminUsers has a field locationId that equals x, but I'm not sure how to do this?
How can I get access to the plucked object so I can check the value of locationId?
Use findWhere instead of pluck. You can give it an object containing all the properties you want to match.
if (util.findWhere(myList.adminUsers, {email: u.email, locationId: u.locationId})) {
u.status = "admin";
}
This should give you the list of admins that are found in the list of users and are in the location ID you provide as a value (I set it as a variable).
const users = [
{
id: "1",
email: "johndoe#gmail.com",
firstname: "John",
lastname: "Doe",
roleid: "1"
},
{
id: "2",
email: "janedoe#gmail.com",
firstname: "Jane",
lastname: "Doe",
roleid: "1"
}
];
const admins = [
{
id: "1",
email: "johndoe#gmail.com",
firstname: "John",
lastname: "Doe",
roleid: "1",
locationId: "123"
}
];
const locationIdToFind = '123';
const adminsWithLocation = _.intersectionWith(admins, users, (admin, user) => _.isEqual(admin.email, user.email) && _.isEqual(admin.locationId, locationIdToFind));
console.log(adminsWithLocation);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>

Convert Array of Objects to Multi Dimensional Array in JavaScript

I an new to java script and have array of objects as following
[{
firstName: "John",
lastName: "Doe",
age: 46
},
{
firstName: "Mike",
lastName: "Jeffrey",
age: 56
}]
I would like to convert this array of objects to multi-dimensional array as following
[
[{
firstName: "John",
lastName: "Doe",
age: 46
}],
[{
firstName: "Mike",
lastName: "Jeffrey",
age: 56
}]
]
I am using the following code to convert to multi dimension array
var actualResult = [];
var arrayLength = inputObj.length;
for (var i = 0; i < arrayLength; i++) {
var tempResult = [];
tempResult.push(inputObj[i]);
actualResult.push(tempResult);
}
where inpuObj is my actual input.Is this the correct way of achieving the scenario?
You can use array#map. Iterate through each object and create an array.
var data = [{firstName: "John",lastName: "Doe",age: 46},{firstName: "Mike",lastName: "Jeffrey",age: 56}],
result = data.map(o => [o]);
console.log(result);

How to add key/value pair in Javascript object at the start

I have following object:
var obj = {"last_name": "john", "age": 23, "city": "London"}
I want to add a new element of first_name at the start of this object to look like this:
{"first_name": "Samuel", "last_name": "john", "age": 23, "city": "London"}
I know I can do obj.first_name = "Samuel" but it adds the new element at the end of the object. How can I add it at the start?
While objects have actually (ES5) no order, you could generate a new object with Object.assign and use the new property as object to start with and assign the given object to it. The new object has properties in creation order.
var object = { last_name: "john", age: 23, city: "London" };
object = Object.assign({ first_name: "Samuel" }, object);
console.log(object);
I tried, It works with spread operator. Do it in below way
var object = { last_name: "john", age: 23, city: "London" };
var newObject= { first_name: "Samuel" };
object = {...newObject, ...object }
o/p: { first_name: "Samuel", last_name: "john", age: 23, city: "London" };
Can do with spread operator, not confident about order
var object = { last_name: "john", age: 23, city: "London" };
var newObj={first_name: "Samuel" ,... object}
console.log(newObj);

Categories

Resources