Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Given the following JSON:
const myJson = {
id: 8,
active: true,
invoice: "2022/1001",
invoiceDate: "2022-02-02",
clientId: 1,
storeId: 1,
total: 76.95,
itens: [
{
id: 11,
quantity: 2,
price: 12.10,
total: 24.20,
productId: 1,
invoiceId: 8
},
{
id: 12,
quantity: 5,
price: 10.55,
total: 52.75,
productId: 2,
invoiceId: 8
}
]
};
I need a simple way to remove two attributes from the each item inside the 'itens' array, the properties are 'id' and 'invoiceId'. I also need to recalculate the 'total', coz I do not trust totally the source of the information, I rather multiply 'quantity' by 'price' myself.
I've produced this rather naive code:
myJson.itens.forEach(item => {
item.total =
item.quantity *
item.price;
delete item.id;
delete item.invoiceId;
});
And it works rather fine, however, no way that it must be it. Looks too lame and laborious to me. I'm exhausted googling for better ways of doing it.
Can it be done better?
Rather than mutating the original data, you could map it to a new object
const myJson = {"id":8,"active":true,"invoice":"2022/1001","invoiceDate":"2022-02-02","clientId":1,"storeId":1,"total":76.95,"itens":[{"id":11,"quantity":2,"price":12.1,"total":24.2,"productId":1,"invoiceId":8},{"id":12,"quantity":5,"price":10.55,"total":52.75,"productId":2,"invoiceId":8}]}
const newObject = {
...myJson, // keep the rest but map "itens"
itens: myJson.itens.map(({ id, invoiceId, ...iten }) => ({
...iten, // everything except "id" and "invoiceId"
total: iten.quantity * iten.price // recalc total
}))
}
console.log("newObject:", newObject)
.as-console-wrapper { max-height: 100% !important; }
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I simply want to get 3 highest price value objects as new array. How would I do that easily ?
For example i got array like this ..
const data =
[ { name: 'x', color: 'red', price: 15 }
, { name: 'y', color: 'black', price: 5 }
, { name: 'z', color: 'yellow', price: 25 }
, { name: 't', color: 'blue', price: 10 }
, { name: 'n', color: 'blue', price: 60 }
]
You can sort the array by the price property (with Array.sort) and get the first three items (with Array.slice):
const arr=[{name:"x",color:"red",price:15},{name:"y",color:"black",price:5},{name:"z",color:"yellow",price:25},{name:"t",color:"blue",price:10},{name:"n",color:"blue",price:60}];
const result = arr.sort((a,b) => b.price - a.price).slice(0, 3)
console.log(result)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I've been working with WP REST Api to migrate an app to a headless wp + react app and got some problems with how WP displays Cats and SubCats.
My idea is to get all the current categories and generate children of based on the father category, those children also can get childrens, since WP cat-subcat structure is infinite.
Category { SubCategory { SubCategory {infinite}}}
I've been trying to generate a new Object that contains this info and iterate in different ways, like pushing the one who has 'parentId' equals to father ID, but constantly getting undefined.
My current logic is something like this:
const fatherCategories = categories.filter((item) => (
item.parent === 0
))
const subCategories = categories.filter((item) => (
item.parent !== 0
))
const subCategories = subCats.forEach((category) => (
subCats.filter((item) => (
category.id === item.parent
))
))
Im 100% that this is not the way i need to get my objective but my knowledge stops here and can't get any solution for this problem, if i know the lenght of the subcategories i will go another way, but without this data, im blocked.
As my previous comment says something like this should work for you:
function isParent(category) {
return category.parent === 0;
}
function findAllchildren(allCategories, currentCategory) {
// const allCategories.filter()
const currCatChildren = allCategories.filter(
(c) => c.parent === currentCategory.id
);
if (currCatChildren.length) {
currCatChildren.forEach((c) => {
c.children = findAllchildren(allCategories, c);
});
}
return currCatChildren;
}
const categories = [
{ id: 1, parent: 0, name: "pc -> 1" },
{ id: 2, parent: 0, name: "pc -> 2" },
{ id: 3, parent: 1, name: "cc -> 3>1" },
{ id: 4, parent: 2, name: "cc -> 4>2" },
{ id: 5, parent: 3, name: "cc -> 5>3" },
{ id: 6, parent: 4, name: "cc -> 6>4>1" },
{ id: 7, parent: 5, name: "cc -> 7>5>3>1" },
];
const finalCategoryTree = categories.filter(isParent).map((parentCategory) => {
const tmp = { ...parentCategory };
tmp.children = findAllchildren(categories, parentCategory);
return tmp;
});
console.log(JSON.stringify(finalCategoryTree));
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Which is more optimized way .filter() + .map() OR .forEach() ?
Here is a sample array of objects:
var personnel = [
{
id: 5,
name: "Luke Skywalker",
pilotingScore: 98,
shootingScore: 56,
isForceUser: true,
},
{
id: 82,
name: "Sabine Wren",
pilotingScore: 73,
shootingScore: 99,
isForceUser: false,
},
{
id: 22,
name: "Zeb Orellios",
pilotingScore: 20,
shootingScore: 59,
isForceUser: false,
},
{
id: 15,
name: "Ezra Bridger",
pilotingScore: 43,
shootingScore: 67,
isForceUser: true,
},
{
id: 11,
name: "Caleb Dume",
pilotingScore: 71,
shootingScore: 85,
isForceUser: true,
},
];
And let say we want to get the final array giving only name and id where isForceUser=true
[ { id: 5, name: 'Luke Skywalker' },
{ id: 15, name: 'Ezra Bridger' },
{ id: 11, name: 'Caleb Dume' } ]
Now there are 2 ways ti solve it :
By using .filter()+.map(), as shown below:
var APersonnel = personnel
.filter((person) => person.isForceUser)
.map((person) => ({ id: person.id, name: person.name }));
By using .forEach() and pushing a new object:
var BPersonnel = [];
personnel.forEach((person) => {
if (person.isForceUser) {
BPersonnel.push({ id: person.id, name: person.name });
}
});
Which one of the solutions defined above is better and why?
These are not the things you should seek performance improvements in. You are talking about 'personnel' here. Which is a fairly limited array set, I imagine. If you are having performance issues, I suggest you use the chrome dev performance tab to see what's causing it.
To answer your question, filter + map is semantically easier for the eye, which again is a personal opinion. Strictly performance wise the forEach is faster, where most likely a basic of for loop is even faster. But again, these are a few milliseconds we are talking about. Which does not justify the cost of rewriting :)
Another way can be to use reduce, less code, and only one loop:
const APersonnel = personell.reduce((acc, person) => {
if (person.isForceUser) {
acc.push({ id: person.id, name: person.name });
}
return acc;
}, []);
The best way is using foreach. Because map and filter are going to create two arrays. foreach doesn't create arrays. So foreach is the best one. look at those statements bellow,
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
I could be wrong, but I'm guessing forEach would be better.
In the first scenario, you are looping across 5 items, and then again across 3 items.
In the second scenario you are just looping across 5 items. And the if in the foreach is effectively being done in the filter anyway.
There may be an exception if you're working with an extremely large set of data because you would have both arrays in memory, but for anything short of that, I would recommend forEach
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have an array with multiple objects.How can i delete an element in a
object.
For example i have attached a image in that i need to delete
organization element.
Please help me out to fix.
var a = {name: 'pardeep', 'sirname': 'jain'}
delete a['name']
console.log(a);
Just use delete keyword for the key like this -
delete objectName['keyName']
Use the delete operator
const deleteAttribute = (array, attribute) => array.map(x => {
// Delete the attribute here
delete x[attribute];
return x;
});
const arr = [{
attr: 'hello',
color: 'red',
organization: 'Good'
}, {
attr: 'world',
color: 'blue',
organization: 'bad'
}];
console.log(deleteAttribute(arr, 'organization'));
You can use map and delete like below
var arr = [{
name: 'hi',
test: 'x',
organization: 'X'
}, {
name: 'guys',
test: 'y',
organization: 'Y'
}];
console.log(arr.map(x => { delete x.organization; return x}));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
IE: I have 2 arrays one with prices, one with names.
The one with prices is longer, and I only want the final array to be the size of the smaller array with only names.
Objects in the prices array:
{
currency: 'BTC',
price: '6500'
},
{
currency: 'NEM',
price: '1'
},
Objects in the name array:
{
currency: 'BTC',
name: 'Bitcoin'
}
The final array should only contain objects that exist in the name array, but also have the price key from the prices array.
{
currency: 'BTC',
name: 'Bitcoin',
price: '6500'
}
I had accomplished this using an NPM package, however the package is old and there is a bug when compiling:
Error while running NPM run build (ERROR in index_bundle.js from UglifyJs)
I also found this answer here: How to merge 2 arrays with objects in one? However none of the answers worked. Neither was the array filtered by the smaller array, but the keys were not combined either.
An alternative is using the function map to generate a new array with the desired output.
This approach uses the function find to retrieve the specific object price related to an object name name.currency === price.currency.
let prices = [{ currency: 'BTC', price: '6500'},{ currency: 'BSS', price: '850'},{ currency: 'USD', price: '905'}],
names = [{ currency: 'BTC', name: 'Bitcoin'},{ currency: 'BSS', name: 'Bolivar'}],
result = names.map(n => Object.assign({}, n, prices.find(p => p.currency === n.currency)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }