Javascript using for...in loop with objects - javascript-objects

Is anyone can help me to found this output.
Sample output:
['milk', 'bread', 'potato']
[20, 15, 10]
Here is the code.
var itemsToBuy = {
milk: {
quantity : 5,
price: 20
},
bread: {
quantity : 2,
price: 15
},
potato: {
quantity : 3,
price: 10
}
}
I have found for first array using Object.keys(itemsToBuy) but not able to found for second array.

User Object.values and map for second array
var itemsToBuy = {
milk: { quantity: 5, price: 20 },
bread: { quantity: 2, price: 15 },
potato: { quantity: 3, price: 10 },
};
const out1 = Object.keys(itemsToBuy);
const out2 = Object.values(itemsToBuy).map(({ price }) => price);
console.log(out1, out2);
// Using for..in loop
const out3 = [];
for(const key in itemsToBuy) {
out3.push(itemsToBuy[key].price)
}
console.log(out3)

Object.values(itemsToBuy).map(item => item.price) should do the trick

Related

I am trying to get a function to search an array of objects and then return the entire object based on the filter

I am trying to get my function working and I can not for the life of me figure out why it isnt. I am trying to use .filter() to search the array of objects to find the object with the tag ketchup. Then return the whole object it is in to the console log
let foodArr = [
{
type: 'Chicken',
rating: 1,
tags: ['chicken', 'free-range', 'no hormones'],
price: 10,
popularity: 80
},
{
type: 'pizza',
rating: 5,
tags: ['pepperoni', 'sauce', 'bread'],
price: 25,
popularity: 56
},
{
type: 'hamburger',
rating: 3,
tags: ['bun', 'patty', 'lettuce'],
price: 8,
popularity: 99
},
{
type: 'wings',
rating: 4,
tags: ['wing', 'bbq', 'ranch'],
price: 12,
popularity: 68
},
{
type: 'fries',
rating: 2,
tags: ['ketchup'],
price: 4,
popularity: 100
}
]
const filteredFood = foodArr.filter(function(obj) {
return obj.tags[''] === 'ketchup'
})
console.log(filteredFood)
const filteredFood = foodArr.filter(function(value){
for (let i=0; i<value.tags.length; i++)
if(value.tags[i] === 'ranch'){
return value.tags[i]
}
}
)
console.log(filteredFood)

Create new array using 2 arrays with Map function in Angular

Is there an efficient way of creating a new array from 2 arrays?
var employees1 = [
{ id: 11, name: 'joe' },
{ id: 12, name: 'mike' },
{ id: 13, name: 'mary' },
{ id: 14, name: 'anne' }
];
var employees2 = [
{ id: 11, message: 'test1' },
{ id: 12, message: 'test2' },
{ id: 13, message: 'test3' },
{ id: 14, message: 'test4' }
];
Iterate employees1 array and get 'message' for matching id from employees2. Resulting in new array:
var employees3 = [
{ id: 11, name: 'joe', message: 'test1' },
{ id: 12, name: 'mike', message: 'test2' },
{ id: 13, name: 'mary', message: 'test3' },
{ id: 14, name: 'anne', message: 'test4' }
];
Is this possible using Map function? Or using a standard foreach suggested?
Iterate over the first array, search for the element in the second array and finally push them to the new array as illustrated below:
var employees3 = [];
employees1.forEach(emp1 => {
const findEmp = employees2.find(emp2 => emp2.id === emp1.id);
if (findEmp) {
employees3.push({
...emp1,
...findEmp
});
}
});
console.log(employees3);
You can use Array#map and Array#find to get the desired output. I am attaching a sample code:
var employees3 = employees1.map(emp => ({
...emp,
...(employees2.find(item => item.id === emp.id) ?? {})
}))

How to check if arrays have the same object React Native [duplicate]

This question already has answers here:
An efficient way to get the difference between two arrays of objects?
(4 answers)
Closed 3 years ago.
I have two arrays:
const array1 = [
{ id: 1, name: 'John', score: 124 },
{ id: 2, name: 'Angie', score: 80 },
{ id: 3, name: 'Max', score: 56 }
]
const array2 = [
{ id: 5, name: 'Lisa', score: 78 },
{ id: 2, name: 'Angie', score: 80 }
]
JSON.stringify(array1) == JSON.stringify(array2) is not a solution, because arrays have different number of objects.
array1.some(item=> array2.includes(item)) doesnt't work too.
If there a solution?
What i would suggest is since your id is unique , so try the below :
const array1 = [
{ id: 1, name: 'John', score: 124 },
{ id: 2, name: 'Angie', score: 80 },
{ id: 3, name: 'Max', score: 56 }
]
const array2 = [
{ id: 5, name: 'Lisa', score: 78 },
{ id: 2, name: 'Angie', score: 80 }
]
var array2Id = {}
array2.forEach(function(obj){
bIds[obj.id] = obj;
});
// Return all elements in A, unless in B
let check = array1.filter(function(obj){
return !(obj.id in array2Id);
});
console.log(check,'there')
if check is an empty array that means both are same otherwise it will give the different objects.
Hope it helps feel free for doubts
Here is a quick solution, maybe not the most performant.
const array1 = [
{ id: 1, name: 'John', score: 124 },
{ id: 2, name: 'Angie', score: 80 },
{ id: 3, name: 'Max', score: 56 },
];
const array2 = [
{ id: 5, name: 'Lisa', score: 78 },
{ id: 2, name: 'Angie', score: 80 },
];
// Index will have -1 if there is no match, otherwise it'll have
// the index of the first found match in array1.
const index = array1.findIndex(array1Item => {
// This will return the index if found, otherwise -1
const match = array2.findIndex(array2Item => {
// return array1Item.id === array2Item.id;
return JSON.stringify(array1Item) === JSON.stringify(array2Item);
});
return match > -1;
});
Instead of stringifying the entire object, if id is unique, you can just compare id as shown in the commented code.
Be advised this could have a complexity of O(n^2) where n is your array sizes. Big arrays may take a while.
Here is it running on PlayCode. It logs index as 1 because the first match is the second item in array1.

Filter an Array based on multiple values

I have the following simple JSON array:
const personList = [
{
id: 1,
name: "Phil"
},
{
id: 2,
name: "Bren"
},
{
id: 3,
name: "Francis Underwood"
},
{
id: 4,
name: "Claire Underwood"
},
{
id: 5,
name: "Ricky Underwood"
},
{
id: 6,
name: "Leo Boykewich"
}
];
And I would like to filter this by passing an array of ids so something like [1,4] would be passed in and it would only return "Phill" and "Claire Underwood"
This is what the function looks like but I know it's wrong attendeeIds is an array that's passed in [1, 4]:
getAttendeesForEvent: (attendeeIds) => {
if (attendeeIds === undefined) return Promise.reject("No attendee id provided");
return Promise.resolve(personList.filter(x => x.id == [attendeeIds]).shift());
}
I haven't used JS in years. I've looked for examples but they all seem too complex for what I'm trying to achieve. So how can I filter this based on an array of id's passed in?
return Promise.resolve(personList.filter(x => attendeeIds.indexOf(x.id) !== -1));
You want to check if the id of each item your looping over exists inside of attendeeIds. Use Array.indexOf inside of the filter to do that.
This will return an array of { id: #, name: String } objects.
If you want to return just the names of those objects, you can do a map afterwards which will transform an array into another array using the function that you provide.
const filteredNames = personList
.filter(x => attendeeIds.indexOf(x.id) !== -1)
.map(x => x.name);
// ['Phil', 'Claire Underwood']
You could do something in these lines. Hope this helps.
const personList = [{
id: 1,
name: "Phil"
}, {
id: 2,
name: "Bren"
}, {
id: 3,
name: "Francis Underwood"
}, {
id: 4,
name: "Claire Underwood"
}, {
id: 5,
name: "Ricky Underwood"
}, {
id: 6,
name: "Leo Boykewich"
}];
let attendeeIds = [1, 5];
let getAttendeesForEvent = () => {
return new Promise(function(resolve, reject) {
if (attendeeIds === undefined) {
reject("No attendee id provided");
} else {
resolve(personList.filter((x) => attendeeIds.includes(x.id)).map((obj) => obj.name));
}
});
}
getAttendeesForEvent().then((data) => console.log(data))

Get diff between two arrays of objects with ES6 or TypeScript

I have the following arrays:
arr1 = [{
id: 1,
name: 'Diego',
age: 23
}, {
id: 2,
name: 'Brian',
age: 18
}]
arr2 = [{
id: 1,
name: 'Diego',
age: 23
}, {
id: 2,
name: 'Brian',
age: 18
}, {
id: 3,
name: 'Pikachu',
age: 88
}]
I need get difference between this two arrays, the espected result is:
arr3 [{id:3, name: 'Pikachu', age: 88}]
How do i solve this problem using ES6 or TypeScript?
I tried using SET, but doesn't worked.
Something like this maybe:
let ids1 = arr1.map(item => item.id);
let ids2 = arr2.map(item => item.id);
let diff = ids1.map((id, index) => {
if (ids2.indexOf(id) < 0) {
return arr1[index];
}
}).concat(ids2.map((id, index) => {
if (ids1.indexOf(id) < 0) {
return arr2[index];
}
})).filter(item => item != undefined);
(code in playground)

Resources