Multiply the object properties - javascript

someone tell me how to multiply object's properties? I need this object multiplied by the count of property price and put together
var menu = [
{
"id": 5,
"price": 13,
"count": 2
},
{
"id": 8,
"price": 7,
"count": 3
},
{
"id": 9,
"price": 17,
"count": 1
}
]
var sum = 0;
for (var key in menu) {
for (var key1 in menu[key]) {
//console.log(key1);
if (key1 == 'price'){
price += menu[key][key1];
}
}
}
but I have no idea how to multiply count property

You can use Array.prototype.map with Array.prototype.reduce.
.map takes a callback function which will multiply the price of each item by the count and creates a new array looking like this:
[26,21,17].
.reduce takes a callback as well, iterating over the new create array summing up the multiplied prices resulting to:
64
let menu = [
{
"id": 5,
"price": 13,
"count": 2
},
{
"id": 8,
"price": 7,
"count": 3
},
{
"id": 9,
"price": 17,
"count": 1
}
]
let sum = menu.map(p => p.price * p.count).reduce((a,b) => a + b)
console.log("Total:",sum)

You probably want something like this:
{
"id": 5,
"price": 13,
"count": 3,
"value": function() {return this.price * this.count;}
}
You can do that by either making an object and adding a prototype (which saves memory and time) or construct it that way each time.
Otherwise you can just do:
var obj = { ... } // your stuff
alert(obj.price * obj.count)

suppose you want to calculate the sum
var menu = [
{
"id": 5, "price": 13, "count": 2 }, {
"id": 8, "price": 7, "count": 3 }, { "id": 9, "price": 17, "count": 1 } ];
var sum = 0, item;
for(item in menu)
{
sum += menu[item].price * menu[item].count;
}
console.log(sum);

Related

Multiple iterations of one array js

I have an array
const head = [
{
"id": 1,
"name": "AK47",
"norms": "15-18",
"times": 2
},
{
"id": 2,
"name": "Deagle",
"norms": "13-21",
"times": 1
}
]
arrays should be created from it according to the number of times properties
Something like that:
const tail = [
{
"id": 1,
"headId": 1,
"time": 1,
"check": 16,
"status": "ok"
},
{
"id": 2,
"headId": 1,
"time": 2,
"check": 14,
"status": "less"
},
{
"id": 3,
"headId": 2,
"time": 1,
"check": 23,
"status": "excess"
}
]
"times": 2 was therefore 2 arrays created. Inside them is the property time meaning which time of times
How can I implement this solution more conveniently and correctly. I will be glad for any help
Your explanation is still a bit unclear, but from what I've understood, the code below might be the answer you're looking for. It loops through the head elements and then loops x number of times, where x equals the times property. It creates an array for each element in head and then flattens it to generate the desired 1D array output.
const head = [{
"id": 1,
"name": "AK47",
"norms": "15-18",
"times": 2
},
{
"id": 2,
"name": "Deagle",
"norms": "13-21",
"times": 1
}
];
let idIdx = 1;
const res = head.flatMap((obj) => {
let arr = [];
for (let i = 0; i < obj.times; i++)
arr.push({
id: idIdx++,
headId: obj.id,
time: i + 1
});
return arr;
});
console.log(res);

How to retrieve specific key value in an array of objects within objects?

I have an array originalArrayData like so:
Expanding:
The value of the first array item, which is an object, is several objects. An example of the contents of the first part of the array is as such:
originalArrayData = [{
"16": {
"id": 22,
"grid_row_id": 5,
"grid_col_id": 16,
"data": "10",
"created_at": "rertte",
"error_mgs": null
},
"header": "Row 2",
"id": 5
},
{
"17": {
"id": 31,
"grid_row_id": 9,
"grid_col_id": 17,
"data": "14",
"created_at": "rtyhtyjtdyj",
"error_mgs": null
},
"header": "Row 1",
"id": 6
},
{
"18": {
"id": 35,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "55",
"created_at": "thrtuhrs",
"error_mgs": null
},
"header": "Row 1",
"id": 6
}...........
Let's say I have an array of ids (these numbers could be random and there isn't always 2. There could be 1, 3, etc. array items)
arrayOfIds: [16 , 17]
If the value of grid_col_id is present anywhere in the arrayOfIds, how can I retrive the 'data' value from each object and put it in its own array?
I know how to retrieve an array of all ids from each first object within the array:
let data = this.arrayList.map((obj) => obj.id);
The above yields: [5,6,7,8,9]. However, it's now correct for what I am attempting. So far I have the following:
var targetArr = []
this.originalArrayData.forEach(item=> {
item.forEach(ins => {
if(arrayOfIds.includes(ins.grid_col_id)
targetArr.push(ins.data)
})
})
which yields an error: TypeError: row.forEach is not a function
My TARGET is: [10, 14, ...]
The target contains 10 and 14 because if you look at the originalArrayData, if grid_col_id is inside arrayOfIds: [16 , 17], then we retrieve the "data" value and put it inside a new array.
How can I achieve the target array?
You can do as follows. See comments in the code for explanation
let od = [{
"16": {
"id": 22,
"grid_row_id": 5,
"grid_col_id": 16,
"data": "10",
"created_at": "rertte",
"error_mgs": null
},
"header": "Row 2",
"id": 5
},
{
"17": {
"id": 31,
"grid_row_id": 9,
"grid_col_id": 17,
"data": "14",
"created_at": "rtyhtyjtdyj",
"error_mgs": null
},
"header": "Row 1",
"id": 6
},
{
"18": {
"id": 35,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "55",
"created_at": "thrtuhrs",
"error_mgs": null
},
"header": "Row 1",
"id": 6
}]
let filter = [16, 17];
//transform the original data into a flat array of objects
let dd = od.map(x =>
//all property values of the object
Object.values(x)
//which are an object (ie filter away primitve types
.filter(y => typeof y === "object"))
//flatten the array of arrays
.flat()
let result = dd
//filter the list of objects for the ids in the filter
.filter(x => filter.includes(x.grid_col_id))
//and get only the data property
.map(x => x.data)
console.log(result);
Here you go:
const input=[{"16":{id:22,grid_row_id:5,grid_col_id:16,data:"10",created_at:"rertte",error_mgs:null},header:"Row 2",id:5},{"17":{id:31,grid_row_id:9,grid_col_id:17,data:"14",created_at:"rtyhtyjtdyj",error_mgs:null},header:"Row 1",id:6},{"18":{id:35,grid_row_id:9,grid_col_id:12,data:"55",created_at:"thrtuhrs",error_mgs:null},header:"Row 1",id:6}];
const arrayOfIds = [16 , 17];
const format = (array) => {
return array.reduce((result, el) => {
const key = Object.keys(el).find((key) => 'object' === typeof el[key]);
if(arrayOfIds.includes(+key)){
result.push(+el[key].data);
}
return result;
}, []);
};
console.log(format(input));
Here's an alternative that more closely resembles your original attempt.
You can use Object.keys, Object.hasOwn and Array.prototype.find to get the key of the property with grid_col_id:
const originalArrayData = [{
"16": {
"id": 22,
"grid_row_id": 5,
"grid_col_id": 16,
"data": "10",
},
"header": "Row 2",
"id": 5
},
{
"17": {
"id": 31,
"grid_row_id": 9,
"grid_col_id": 17,
"data": "14",
},
"header": "Row 1",
"id": 6
},
{
"18": {
"id": 35,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "55",
},
"header": "Row 1",
"id": 6
}]
const arrayOfIds = [16, 17]
const targetArr = []
originalArrayData.forEach(d => {
const keyOfObjectWithGridCol =
// Get all keys of the object as an array
Object.keys(d)
// Get the key of the nested object that has grid_col_id
.find(key => Object.hasOwn(d[key], 'grid_col_id')) // Find property
if (arrayOfIds.includes(d[keyOfObjectWithGridCol].grid_col_id)) {
targetArr.push(d[keyOfObjectWithGridCol].data)
}
})
console.log(targetArr) // [10, 14]

Update a nested Array Value with Another Nested Array Data in JavaScript

I have a 2 nested object array, I would like to update the first array's nested array value with the second array nested array values. I had done a brute force approach but I would like to improve my logic.
The first array is
[{
"name": "data",
"values": [{
"cid": 1,
"ccount": 0
},
{
"cid": 2,
"ccount": 0
},
{
"cid": 3,
"ccount": 0
}
]
},
{
"name": "data1",
"values": [{
"cid": 1,
"ccount": 0
},
{
"cid": 2,
"ccount": 0
},
{
"cid": 3,
"ccount": 0
}
]
}
]
and the second array looks like
[{
"fName": "End",
"version": 1,
"cValues": [{
"id": 1,
"count": 2
},
{
"id": 2,
"count": 3
},
{
"id": 3,
"count": 4
}
]
},
{
"fName": "Start",
"version": 2,
"cValues": [{
"id": 1,
"count": 2
},
{
"id": 2,
"count": 12
},
{
"id": 3,
"count": 22
}
]
}
]
I would like to update the count of nested array values inside the first array based on the id of the second nested array values.
I had done a brute force approach, my code is
for (let i = 0; i < (arr1.length && arr2.length); i++) {
arr1[i].values[i].sort(this.sortByProperty("cid"));
for (let j = 0; j < (arr1[i].values[i].length && arr2[i].cValues.length); j++) {
if (arr1[i].values[j].cid == arr2[i].cValues[j].id) {
arr1[i].values[j].cCount = arr2[i].cValues[j].count;
}
}
}
sortByProperty(property) {
return function (a, b) {
if (a[property] > b[property])
return 1;
else if (a[property] < b[property])
return -1;
return 0;
}
}
Can anyone help me to improve my code logic?

Check if array of objects, which also contain nested arrays with objects, are the same, if so, combine them into one object and add the keys together

I would need to check if the objects in the "food" array are equal to each other, and the ones that are - combine into one adding amount and mody.amount and leaving the rest unchanged. This is just for better order data displaying. I tried with lodash library and reduce but but I don't know exactly how to construct this function that nested objects(mody) adds values ​​as well, and in case isEqual returns false keep the object while concurrently concatenating the identical ones.
What I tried:
obj1.reduce((prev, next) => _.isEqual(prev, next) ? {...prev, amount: prev.amount + next.amount} : next
Now it looks like that:
const food = [
{
"id": 1,
"name": "chicken",
"price": 6,
"amount": 1,
"mody": [
{
"id": 33,
"name": "cheese",
"price": 1,
"amount": 1
},
{
"id": 34,
"name": "chips",
"price": 2,
"amount": 1
}
]
},
{
"id": 1,
"name": "chicken",
"price": 6,
"amount": 1,
"mody": [
{
"id": 33,
"name": "cheese",
"price": 1,
"amount": 1
},
{
"id": 34,
"name": "chips",
"price": 2,
"amount": 1
}
]
},
{
"id": 2,
"name": "pizza",
"price": 6,
"amount": 2,
"mody": [
{
"id": 12,
"name": "extra cheese",
"price": 2,
"amount": 1
}
]
}
]
and would need something like that:
const food = [
{
"id": 1,
"name": "chicken",
"price": 6,
"amount": 2,
"mody": [
{
"id": 33,
"name": "cheese",
"price": 1,
"amount": 2
},
{
"id": 34,
"name": "chips",
"price": 2,
"amount": 2
}
]
},
{
"id": 2,
"name": "pizza",
"price": 6,
"amount": 2,
"mody": [
{
"id": 12,
"name": "extra cheese",
"price": 2,
"amount": 1
}
]
}
]
The algorithm to sum the food amounts and mody amounts are almost the same, the difference is that for each food that has the same id we will sum the mody amount. To make the algorithm simpler I used a dictionary as the accumulator on the reduce function so we have a unique element per key. This element will be our final food or mody with the amount sum.
Mody sum algoritm:
const sumMody = (modyAccumulator, currentMody) => {
//Get the stored mody in the accumulator dictionary or null if it the mody is not stored
const storedMody = modyAccumulator[currentMody.id] ?? null
// if mody is null then add mody to the dictionary using its id as key
if (!storedMody) {
modyAccumulator[currentMody.id] = currentMody
} else {
//Mody is stored then sum amount
storedMody.amount += currentMody.amount
}
return modyAccumulator
}
The food sum algoritm is the same as the sumMody, the only difference is that it calls the sumMody function when the foods are equal:
const sumFood = (foodAccumulator, currentFood) => {
//Get the stored foodin the accumulator dictionary or null if it the food is not stored
const storedFood = foodAccumulator[currentFood.id] ?? null
// if food is null then add food to the dictionary using its id as key
if (!storedFood) {
foodAccumulator[currentFood.id] = currentFood
} else {
//Food is stored then sum food amount
storedFood.amount += currentFood.amount
//Create a list with mody from both foods
const modyList = [...storedFood.mody, ...currentFood.mody]
//Use reduce passing the sumMody callback function and initialize the accumulator with a dictionary
const modySumDictionary = modyList.reduce(sumMody, {})
/* The function above return a dictionary where the identifier is the mody.id
and the value is the mody. We only need the values from that dictionary so
we use Object.values to extract all the values. */
storedFood.mody = Object.values(modySumDictionary)
}
return foodAccumulator
}
To execute both sums:
//As explained before the reduce function will return a dictionary so we use Object.values to get only the values
const result = Object.values(food.reduce(sumFood, {}))
console.log(result)
Algoritm without comments:
const sumMody = (modyAccumulator, currentMody) => {
const storedMody = modyAccumulator[currentMody.id] ?? null
if (!storedMody) {
modyAccumulator[currentMody.id] = currentMody
} else {
storedMody.amount += currentMody.amount
}
return modyAccumulator
}
const sumFood = (foodAccumulator, currentFood) => {
const storedFood = foodAccumulator[currentFood.id] ?? null
if (!storedFood) {
foodAccumulator[currentFood.id] = currentFood
} else {
storedFood.amount += currentFood.amount
const modyList = [...storedFood.mody, ...currentFood.mody]
const modySumDictionary = modyList.reduce(sumMody, {})
storedFood.mody = Object.values(modySumDictionary)
}
return foodAccumulator
}
const result = Object.values(food.reduce(sumFood, {}))
console.log(result)
Reference to Object.values

javascript vuejs object array returning only one item in the loop

I am trying to iterate over an array of objects instead its returning only one item here is the code:
setAll(){
var result =this.cart;
for (var key in result) {
var obj = result[key];
}
return obj.price;
}
and the test data
[ { "id": 5, "price": 3200, "quantity": 8, "name": "juice" }, { "id": 6,
"price": 300, "quantity": 6, "name": "rice" }, { "id": 8, "price": "100",
"quantity": 1, "name": "water" }, { "id": 7, "price": "4500", "quantity":
1, "name": "meat" } ]
You are iterating through the array and only returning the last object. This code:
for (var key in result) {
var obj = result[key];
}
does nothing other than set obj to the last item in the list.
Right now object will be set to its value from the last iteration through the loop, and you will return the price of that object only.
your function replace to
setAll(){
return this.cart.map(({ price }) => +price);
}
i am write jsfiddle example for your question
This worked for me:
setAll(){
var result =this.cart;
var res=Object.keys(result).map(function(key){
return parseInt(result[key].price);
});
return res;
},

Categories