This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 4 months ago.
Here's a list of objects for example:
const products = [
{
name: "Cherry",
price: 10,
quantity: 0,
productId: 1,
image: "../images/cherry.jpg"
},
{
name: "Orange",
price: 15,
quantity: 0,
productId: 2,
image: "../images/orange.jpg"
},
{
name: "Strawberry",
price: 3,
quantity: 0,
productId: 3,
image: "../images/strawberry.jpg"
}
];
I want to get the other properties of an object from the list using its productId. I'm a beginner in JavaScript so I can't seem to figure this out. Any help would be highly appreciated!
products.find((product) => product.productId === pid) // where pid is the id of the product you want to find
What i understand from your description is that you want to find out the product property of a specific items from the list for that you can use
==ES6==
products.filter( (item) => { return item.productId==productId})
==Vanila js==
products.filter(function(item) { return item.productId==productId})
Related
This question already has an answer here:
Lodash uniqBy update the latest value
(1 answer)
Closed 9 months ago.
I am working on one project where I need to remove duplicate values from JSON array object with some specification in react JS. I have tried to remove using _.uniqBy but in the output it took very first value from duplicate value which is I don't want.
Suppose You have an array JSON like:
[ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ]
using _.uniqBy I got [ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }] this output.
but I want [ { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ] this output.
As you can see I want output whose name is alice not bob along with id:1.
Can anyone help me?
Thank you.
My first thought is to use a reduce, and shove the items in a map, then get the values:
Object.values(items.reduce((map, item) => ({ ...map, [item.id]: item }), {}))
This is probably not very efficient though if you're dealing with large arrays of have performance concerns.
It's a quick and dirty one-liner. If you want something more efficient I'd take a look at the lodash source code and tweak it to your needs or write something similar:
https://github.com/lodash/lodash/blob/2f79053d7bc7c9c9561a30dda202b3dcd2b72b90/.internal/baseUniq.js
This question already has answers here:
How to efficiently count the number of keys/properties of an object in JavaScript
(19 answers)
Closed 11 months ago.
how to get object length in pure javascript in this code
let myFavGames = {
"Trinity Universe": {
publisher: "NIS America",
price: 40,
},
"Titan Quest": {
publisher: "THQ",
bestThree: {
one: "Immortal Throne",
two: "Ragnarök",
three: "Atlantis",
},
price: 50,
},
YS: {
publisher: "Falcom",
bestThree: {
one: "Oath in Felghana",
two: "Ark Of Napishtim",
three: "origin",
},
price: 40,
},
};
// Code One => How To Get Object Length ?
let objectLength = ?;
You can use Object.keys() to get the number of keys in your object:
const myFavGames = {
"Trinity Universe": {
publisher: "NIS America",
price: 40,
},
"Titan Quest": {
publisher: "THQ",
bestThree: {
one: "Immortal Throne",
two: "Ragnarök",
three: "Atlantis",
},
price: 50,
},
YS: {
publisher: "Falcom",
bestThree: {
one: "Oath in Felghana",
two: "Ark Of Napishtim",
three: "origin",
},
price: 40,
},
};
const objectLength = Object.keys(myFavGames).length;
console.log(objectLength); // 3
The Object.keys() method returns an array of a given object's own enumerable property names.
console.log(Object.keys(myFavGames).length);
There are several questions with answers on StackOverflow which shows how to find Cartesian product for various simple arrays. And a wonderful article on RosettaCode. But I can't find any solution for my problem.
I have an array of object with items, let's call it items:
let items = [{
id: 1
quantity: 2
field: "other_field"
},
{
id: 2
quantity: 3
field: "other_field"
}]
Every item in this array have a pricing/crafting method and we could receive it by request.
let pricing = getPricing(id) //item id
/*
Which will return to us:
*/
pricing = [
{pricing_id: 1, reagent_items: [/*array of objects, fields exactly items*/]},
{pricing_id: 2, reagent_items: [/*array of objects, fields exactly items*/]}
]
CARTESIAN PRODUCT PROBLEM:
As you may already understand, according to the answer's title, I want to receive all possible combinations of items AND reagent_items from pricing methods.
For example, if we have two items and all every item (of this 2) have just one pricing method, there will be 4 different combinations:
2 default items from items
first default item from items (item[0]) and all all reagent_items from getPricing for item[1]
second default item from items (item[1]) and all all reagent_items from getPricing for item[0]
both reagent_items from getPricing for both default items
I literally can't push reagent items to items (or remove item from items) array, because items can be the same (include each other) Instead of it, I am using my own Array.prototype.method for adding/removal items from items array. It does just the same as push/slice but in more elegant way, manipulating with id and quantity fields.
The actual problem lies in the field of arrays.length and for ... loop.
When we evaluate default Cartesian product we know before the array.length and it's elements.
But in my case I should getPricing every items, then receive array of methods..
Schema:
It's like:
Default: I_1 I_2 ... N
/ \ / \ / \
Get Pricing: [I_A, I_B][I_B, I_C] [IN_J, IN_K],
[IN_Y, IN_X, IN_Z],
So it's not about finding: Cartesian([I_A, I_B],[I_B, I_C]) but something like:
I_1 + I_2
I_1 + (I_B, I_C)
(I_A, I_B) + I_2
(I_A, I_B) + (I_B, I_C)
...
So default item includes each others and their reagent_items and it's simple to find all combinations of two items, but when it's become 3+..
My current pseudo code for now:
/* inside async*/
...
let ArrayOfPricing = [] //length 2, where each Array represent Array of `pricing` for each item
Promise.all(items.map(async item => {
const itemPricing = await getPricing(item.id);
ArrayOfPricing.push(itemPricing );
})
/**And what's next? **/
for (let item of items) {
}
So I can't understand what should I do next, at this stage.
Should I loop/iterate every item? But if so, even if I iterate every item one-by-one and change/remove it and add it's reagent_items (for every pricing) I still don't change the next item/element in array of items and it's length more then just 2, then I won't receive all the combinations, it will be like:
for items
↓
item[1] → for pricing
→ for reagent_items
↓
replace item[1] for all reagent_item
item[2] /** they are still there, but I need iterate over it's pricing , too **/
item[3]
or I could calculate all possible combinations by looking for items length and all pricing length and then form and empty new array with fixed length and push to all the combinations. But if I iterate over it for push with for loop... I should combine items and it will be for loop, inside for loop, inside for .. loop..
So to be honest I am out of ideas. I don't ask to write full working code instead of me, but to point me the way out of this loop. How to get every combination for every item and "baby-items" inside of it? How many cycles should I use then? I'll be grateful for any useful idea/pseudocode/post link which will help me to deal with this case. I'm also here and will check all the comments and answers below.
UPD a simple version of «from what I get, to what I want»
from this:
[
{
field: "original, can be cloned for every combination",
items:
[
{id: 1, quantity: 2},
{id: 2, quantity: 3}
]
}
]
to:
[
{
field: "original",
items:
[
{id: 1, quantity: 2},
{id: 2, quantity: 3}
]
},
{
field: "combination1",
items:
[
{id: 11, quantity: 1}, //from getPricing(item[0])
{id: 12, quantity: 1}, //from getPricing(item[0])
{id: 2, quantity: 3}
]
},
{
field: "combination2",
items:
[
{id: 1, quantity: 2},
{id: 22, quantity: 3} //from getPricing(item[1])
{id: 23, quantity: 3} //from getPricing(item[1])
]
},
{
field: "combination3",
items:
[
{id: 11, quantity: 1}, //from getPricing(item[0])
{id: 12, quantity: 1}, //from getPricing(item[0])
{id: 22, quantity: 3} //from getPricing(item[1])
{id: 23, quantity: 3} //from getPricing(item[
]
}
//can be any length according to getPricing of every item, and I modify original array, but we could create a new one.
]
As I promised, I have found a solution of my problem and I'd like to share it with StackOverflow Community.
Pseudo-code:
let array = [
{
field: "original, can be cloned for every combination",
items:
[
{id: 1, quantity: 2},
{id: 2, quantity: 3}
]
}
]
for (let element of array) {
let MethodsCombinations = [];
for await (let forCombinations of element.items.map((item, i) => {
return getMethod(item.id) //get Method for each item)
})) {
MethodsCombinations.push(forCombinations)
}
/* Cartesian product */
let vanilla_CartesianProduct = MethodsCombinations.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
/* Return array of arrays, with objects inside like default array */
/**
* Other logic with two for loops and merging all the combinations and quantities
* with (my own) modified Array.prototype.addItemToArray
*/
}
I am very grateful to this Nina Scholz's answer and her awesome StackOverflow profile with all answers about combinations/permutations and for providing a support.
I am trying to sort an array of dynamic key / values (Object) based on a property in the object. Can someone please provide me an example of how to do this. Ill try to create a similar structure to my issue
Order Class:
export class order {
id: number;
productRank: number;
productId: number;
productName: string;
}
There is a storeOrders observable array of orders in my component
storeOrders$: Observable<Array<orders>>;
The key in the orders array is dynamically generated and is stored with the key/value containing as key and order object as value
then the orders object for example is something like:
let orders = {
12_123: { id: 123, productRank: 3, productId: 23, productName: 'shirt'},
23_124: { id: 124, productRank: 1, productId: 14, productName: 'cologne'},
67_124: { id: 125, productRank: 2, productId: 45, productName: 'belt' }
}
When i subscribe to this data, how can I iterate over the storeOrders array and sort items based on the productRank. I have been trying to get this right but was not able to get this working, can someone please point out how to iterate over dynamic keys in an array and do a sort based on a property in the value object? Thank you, your helps really appreciated!
Your orders should be a object as below,
orders = {
12_123: { id: 123, productRank: 3, productId: 23, productName: 'shirt' },
23_124: { id: 124, productRank: 1, productId: 14, productName: 'cologne' },
67_124: { id: 125, productRank: 2, productId: 45, productName: 'belt' }
};
you can form the values by using Object.values(orders)
I use sortBy from lodash library as I'm used to it and you get the sorted values as
console.log(sortBy(Object.values(orders),['productRank']));
Stackblitz
to order a dynamic array of keys/values you can do this :
example of array :
arr = [
{de : 'germany'},
{fr : 'france'},
{uk : 'united kingdom'},
{tn : 'tunisia'}
]
arr.sort((a, b) => {
const a_key = Object.keys(a);
const a_value = a[a_key];
const b_key = Object.keys(b);
const b_value = b[b_key];
if (a_value == b_value) return 0;
return a_value > b_value ? 1 : -1;
});
that's all !
This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 8 years ago.
i want to get property value from javascript object list, i have a list
var cars = [{ id: 1, name: 'Audi' }, { id: 2, name: 'BMW' }, { id: 1, name: 'Honda' }];
Now i want get id or name property value by using for loop like this
var cars = [{ id: 1, name: 'Audi' }, { id: 2, name: 'BMW' }, { id: 1, name: 'Honda' }];
var items=[];
var firstProp='id';
for (var i = 0; i < model.length; i++) {
//original work
items.push({ value: model[i].firstProp});//here is the problem
}
please give good advise, thanks.
If I understand your problem correctly, you should use square bracket notation instead of dot notation:
//..
items.push({ value: model[i][firstProp]});//here is the problem
You should do like this
items.push({ value: model[i][firstProp]});
the . notation expects the firstProp to be present as a key in dictionary, since the firstProp is a variable that contains a string you should use [] notation.