This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 years ago.
I have this json. I only care about the uniqueIDs.
How can I get ONLY the uniqueID values delivered back to me as a comma separated list, ie, 11111, 22222? (I need to create my own array.) I can't edit the json below - I am just trying to parse the value I care about out of it....
{
products: [{
type: "Unique",
name: "Joe",
description: "Joes Description",
uniqueID: "11111"
}, {
type: "Unique",
name: "Jane",
description: "Janes Description",
uniqueID: "22222"
}]
}
Thought it would be this easy but its not...
$data['uniqueID'][0]
Use map function:
var foo = {
metadata: {
products: [{
type: "Unique",
name: "Joe",
description: "Joes Description",
uniqueID: "11111"
} {
type: "Unique",
name: "Jane",
description: "Janes Description",
uniqueID: "22222"
}]
}
}
var ids = foo.metadata.products.map(x => x.uniqueID);
And if you are not familiar with arrow function:
var ids = foo.metadata.products.map(function(x){
return x.uniqueID;
});
The Underscore Way
You can use underscore js _.pluck() or _.map() function.
var data = {
metadata: {
products: [{
type: "Unique",
name: "Joe",
description: "Joes Description",
uniqueID: "11111"
},
{
type: "Unique",
name: "Jane",
description: "Janes Description",
uniqueID: "22222"
}]
}
};
//Use plunk method
var uniqueIDArr = _.pluck(data.metadata.products, 'uniqueID');
console.log(uniqueIDArr);
//=> ["11111", "22222"]
//Use map function
var uniqueIDArr = _.map(data.metadata.products, function(obj) {
return obj.uniqueID;
});
console.log(uniqueIDArr);
//=> ["11111", "22222"]
<script src="https://cdn.jsdelivr.net/underscorejs/1.8.3/underscore-min.js"></script>
You can use Array.prototype.map() to create a new array and chain a Array.prototype.join() to get the uniqueIDsString in a single line:
var obj = {metadata: {products: [{type: "Unique",name: "Joe",description: "Joes Description",uniqueID: "11111"}, {type: "Unique",name: "Jane",description: "Janes Description",uniqueID: "22222"}]}},
uniqueIDsString = obj
.metadata
.products
.map(function(product) {
return product.uniqueID;
})
.join(', ');
console.log(uniqueIDsString);
Related
I've been looking at a problem for hours and failing to find a solution. I'm given an array of customer objects.
In each customer object is an array of friends.
In the array of friends is an object for each friend, containing some data, including a name key/value pair.
What I'm trying to solve for: I'm given this customers array and a customer's name. I need to create a function to find if this customer name is in any other customer's friend lists, and if so, return an array of those customer's names.
Below is a customer list. And as an example, one of the customers is Olga Newton. What the code should be doing is seeing that Olga Newton is a customer and is also in the friends lists of Regina and Jay, and should be returning an array of Regina and Jay.
I thought I could do this simply with a filter function, but because the friends list is an array with more objects, this is adding level of complexity for me I can't figure out.
Below is a customer array. The out put should be
['Regina', 'Jay']
and what I've gotten has either been
[{fullCustomerObj1}, {fullCustomerObj2}]
or
[ ]
What am I missing?
Here is the customer array:
var customers = [{
name: "Olga Newton",
age: 43,
balance: "$3,400",
friends: [{
id: 0,
name: "Justice Lara"
}, {
id: 1,
name: "Duke Patrick"
}, {
id: 2,
name: "Herring Hull"
}, {
id: 3,
name: "Johnnie Berg"
}]
}, {
name: "Regina",
age: 53,
balance: "$4,000",
friends: [{
id: 0,
name: "Cheryl Kent"
}, {
id: 1,
name: "Cynthia Wells"
}, {
id: 2,
name: "Gutierrez Waters"
}, {
id: 3,
name: "Olga Newton"
}]
}, {
name: "Jay",
age: 28,
balance: "$3,000",
friends: [{
id: 0,
name: "Cross Barnett"
}, {
id: 1,
name: "Raquel Haney"
}, {
id: 2,
name: "Olga Newton"
}, {
id: 3,
name: "Shelly Walton"
}]
}];
Use filter and map, please.
function friends(c, name){
return c.filter((a) => {
return a.friends.map(b => b.name).includes(name)
}).map(a => a.name);
}
console.log(friends(customers, "Olga Newton"));
// ['Regina', 'Jay']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
We look to an array (friends[]) inside anther (customers[]), So used two for loops, the first determine witch customer will look for his friends, and the second the array will search inside, then set if statement if the cust name is inside friends[]: adding the customer name to customerFriends[] array, At the end return the customerFriends[].
let cust = "Olga Newton"; // Get the customer name who you look for his friends.
const findFriend = (cust, arrs) => { // Create findFriend function.
let customerFriends = []; // Create an array to set the result to it.
for (let i = 0; i < arrs.length; i++) { // For each Customer.
for (const arr of arrs[i].friends) { // For each Friend.
if (arr.name === cust) { // Use Strict equality to find Customer name in friends[].
customerFriends.push(arrs[i].name); // Add the customer name to the customerFriends[].
}
}
}
return customerFriends;// Return the final results.
}
console.log(findFriend(cust, customers)); // Call the function.
I have a js file that is just a an array with the name and type of person. I am trying to write a function in my other file to iterate through that array of objects and return just the object that matches a certain criteria. Here is my code.
person.js
export const persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
utils.js
// params initialized already
person_type = params.subType
const name = persons_options.map((option) => {
if(person_type === option.type){
return option.name
}
})
const person = name
The issue is I know map creates a new array so the output is ,,Phil. How would I just return one of the object names instead of all of them.
find() will do the work
let persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
let obj = persons_options.find(o => o.type === 'Developer');
//to return name
console.log("name",obj.name);
console.log(obj);
You need to use the find function.
See here the list of functions that you can call on an array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods
filter might best suit your case if multiple results may be returned.
I have this object of objects and i want to update this object of objects using the id that each object have this is my code:
lists = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' }
}
function updateItem(id, property,value) {
return (lists[id] = { ...lists[id], [property]: value });
}
if i put it like this it works but i want to do it with just two parameters. Like this:
function updateItem(id, property) {
return (lists[id] = { ...lists[id], property);
}
If you are sure to call the update function with an object
lists = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' }
}
function updateItem({id, netWorth}) {
return (lists[id] = { ...lists[id], netWorth });
}
console.log(updateItem({id:'id3', netWorth: '$200M'} ))
Two ways you can do this:
OPTION 1
You can instead pass the id of the object, and pass a simple object representing a property with it's corresponding value like propertyObj= { propertyName: propertyValue}. And then spread that object within the main object defined by that id:
let lists = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' }
}
// You can pass an id, and a simple object updating the targeted property
function updateItem(id, propertyObj) {
lists[id] = { ...lists[id], ...propertyObj};
}
// test for the updateItem
updateItem("id3", {"name": "Steve Jobs"});
//Let's print and see if it was updated.
console.log(lists);
OPTION 2
Another option would be to associate the updateItem() function with the object itself and set it as a method, since we're dealing with properties, why not?
let list = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' },
// let's defined update method that receive same params
update: function(id, propertiesObject){
this[id] = {...this[id], ...propertiesObject};
}
}
// Let's update the list using it's built-in update() method
list.update("id3", {"name": "Jeff Bezos"});
// Let's print the Updated list
console.log(list);
// NOTE: your object can have many properties in it that you wish to update in your original list.
Here is my array of objects, where I want to get specific value.
{ customerName: "Jay", Purchased: "phone", Price: "€200" },
{ customerName: "Leo", Purchased: "car", Price: "€2000" },
{ customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];
in this function I get all values together. But I want specific value in order to show smth like this in console using for of and for in statements. "Dear Jay thank you for purchase of a phone for the price of €200 "
function getValue(){
for(let key of customerData){
for(let value in key){
console.log(key[value]) //I get all values
//console.log(value) // I get all keys
}
}
}
getValue();```
You don't need multiple for loop for this. You can do this using one forEach() loop and template literal like:
var customerData = [{ customerName: "Jay", Purchased: "phone", Price: "€200" },
{ customerName: "Leo", Purchased: "car", Price: "€2000" },
{ customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];
function getValue() {
customerData.forEach(x => {
console.log(`Dear ${x.customerName} thank you for purchase of a ${x.Purchased} for the price of ${x.Price}`)
})
}
getValue();
var customerData = [{ customerName: "Jay", Purchased: "phone", Price: "€200" },
{ customerName: "Leo", Purchased: "car", Price: "€2000" },
{ customerName: "Luk", Purchased: "Xbox", Price: "€400" },
]
function getValue(){
for(let key of customerData){
for(let value in key){
console.log(key[value]) //I get all values
break;
//It Work
}
}
}
getValue();
By passing the object position in the array as a parameter for the function you can get the single object keys
function getValue(data){
for(let key of Object.values(data)){
console.log(key)
}
}
getValue(a[1]);
// Output
Leo car €2000
You need to pass the name of the customer you're looking for and the data you want about them. Then you can use Array.filter() and Array.map()
Then you can put the functions into a template literal to get your result.
let customerData=[{customerName:"Jay",Purchased:"phone",Price:"€200"},{customerName:"Leo",Purchased:"car",Price:"€2000"},{customerName:"Luk",Purchased:"Xbox",Price:"€400"}]
function getValue(name, otherKey) {
return customerData.filter(obj => obj.customerName === name).map(obj => obj[otherKey])[0]
}
console.log(getValue("Jay", "Purchased"))
console.log(getValue("Luk", "Price"))
let str = `Dear Jay thank you for purchase of a ${getValue("Jay", "Purchased")} for the price of ${getValue("Jay", "Price")}`
console.log(str)
I have an array of objects and the definition for an object looks something like this:
export class AccountInfo {
accountUid: string;
userType: string;
firstName: string;
middleName: string;
lastName: string;
}
NOTE: The reason I don't have userType as an enum is because the object is populated by a database call and I couldn't figure out a clean way to have the string returned from the db populate the enum.
I want to sort the array so that objects with a userType of 'STAFF' appear first, followed by 'TEACHER', then 'PARENT', then 'STUDENT'.
You can store the order in an array, then just use indexOf with sort to achieve your goal. See the code example below:
const humans = [{
accountUid: "1",
userType: "TEACHER",
}, {
accountUid: "2",
userType: "STAFF",
}, {
accountUid: "3",
userType: "STUDENT",
}, {
accountUid: "4",
userType: "PARENT",
}];
const order = ['STAFF', 'TEACHER', 'PARENT', 'STUDENT'];
const result = humans.sort((a, b) => order.indexOf(a.userType) - order.indexOf(b.userType));
console.log(result)
If you can't use ES6, just use:
humans.sort(function(a, b){
return order.indexOf(a.userType) - order.indexOf(b.userType);
});
Here is another way to do it, probably have an order object to store the orders
const actionOrder = {
"EAT" : 1,
"SLEEP" : 2,
"PLAY" : 3,
} as const;
const users = [{
name: "Mike",
action: "PLAY"
}, {
name: "John",
action: "EAT"
}, {
name: "Harry",
action: "SLEEP"
}
];
users.sort((a,b) => {
return actionOrder[a.action] - actionOrder[b.action];
});
console.log(users);