How to merge 2 arrays with similar objects? [closed] - javascript

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; }

Related

How to get second duplicate value rather than first value from JSON Array in React JS using lodash? [duplicate]

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

delete and modify properties in array inside json object [closed]

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; }

How do I sort in the front end with javascript an array of items based on other fields inside the item [duplicate]

This question already has answers here:
How to sort an array of objects by multiple fields?
(38 answers)
Closed 2 years ago.
I am trying to create 2 sort types in my FE with javascript for my items that come from the backend but I don't know what the logic should look like for it. Where can I read about something like this?
The first way would be to sort them by the date (The most recent first)
The second way would be to sort them by the total number of the awards (Highest number first)
This is how my data looks like:
[
{
awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
{
awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
{
awards: {awardOne: 2, awardTwo: 3, awardThree: 2}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
]
Here is an example sorting the data by number of awards in each object: code sandbox. I'm reducing the items in each awards object to a single value and comparing those.
To sort by date, you can use localeCompare like others have pointed out and use a similar pattern.
Update: I just added an working example of sorting by date to the same sandbox
I am thinking you can sort the items by date lexiographically.
Using String.prototype.localeCompare your code would something like
data.sort((a, b) => {
return ('' + a.createdAt).localeCompare(b.createdAt);
}
Source
To sort by number of awards you would need a smaller function, that calculates number of awards, and then write something like:
data.sort((a, b) => {
return (calcNumOfAwards(a) - calcNumOfAwards(b))
}

Delete Documents that have the same of certain field [duplicate]

This question already has answers here:
MongoDB Duplicate Documents even after adding unique key
(4 answers)
mongodb get distinct records
(6 answers)
Closed 3 years ago.
I have a data in MongoDB and I want to remove all the duplicated Documents. The problem is MongoDB assigns each item a unique _id so I can't just delete the duplicated items. I have a field in each Document called name and I want to delete the items that have the same name.
For example:
[{_id: 5c7e423f0bdaa9aeb5399e90,
name ="A"
grade = 16
enrolled ="dddh"
},
{_id: 5c7e423f1bdaa9aeb5399e90,
key ="B"
grade =17
note ="ddddd"
},
{_id: 5c7e423d0bdaa9aeb5399e90,
key ="B"
score =17
note ="ddddd"
}]
to:
[{_id: 5c7e423f0bdaa9aeb5399e90,
name ="A"
grade = 16
enrolled ="dddh"
},
{_id: 5c7e423f1bdaa9aeb5399e90,
name ="B"
grade =17
enrolled ="ddddd"
}]
The list might be big so is there any efficient way to do it?
First note your structure contains a lot of syntax errors. Now, one solution is to use Array.reduce() over your original array of objects to generate a new object using the name properties as the keys of this new object. This will ensure you will end up with only one object associated per name property. Finally, you can use Object.values() to get your desired output.
let input = [
{
_id: "5c7e423f0bdaa9aeb5399e90",
name: "A",
grade: 16,
enrolled: "dddh"
},
{
_id: "5c7e423f1bdaa9aeb5399e90",
name: "B",
grade: 17,
note: "ddddd"
},
{
_id: "5c7e423d0bdaa9aeb5399e90",
name: "B",
score: 17,
note: "ddddd"
}
];
let res = input.reduce((acc, curr) =>
{
acc[curr.name] = acc[curr.name] || curr;
return acc;
}, {});
console.log(Object.values(res));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

When to use arrays within JavaScript objects (or mix them)? [closed]

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 8 years ago.
Improve this question
Very often I see data structures like this:
var settings = {
languages: [
{
language: 'English',
translation: 'English',
langCode: 'en',
flagCode: 'us'
},
{
...
}
]
};
Or this:
var settings = {
languages: [
{
'en' : {
language: 'English',
translation: 'English',
flagCode: 'us'
}
},
{
...
}
]
};
And this can go many levels deep (within an object there are often other arrays containing further objects)...
Adding arrays brings in another level of complexity when arrays have to be looped through to find a certain object, if we don't know its position in the array. But even if know its position it's still more complicated to use than using purely nested objects, where everything can easily be referred to, using dot notation. Like in this case:
var settings = {
languages: {
'en' : {
language: 'English',
translation: 'English',
flagCode: 'us'
},
'de' : {
...
}
}
};
So when is it a good idea to use arrays within objects and when not?
My simple answer
Use objects ({...}) when you need a collection of key:value pairs
Use arrays ([...]) when you need a collection of objects
Other differences
arrays are ordered, objects are not
arrays are automatically indexed with numbers, objects require you to specify an index
arrays have a .length property, objects do not
There can be multiple reason behind doing this. One of them is,
When you need object in specific order array is helpful here. i.e. in your first example
var settings = {
languages:
{
language: 'English',
translation: 'English',
langCode: 'en',
flagCode: 'us'
},
{
...
}
};
the inner object may shuffle it's position, when it's inside an array it will resides at it's index only.
How would you like your data structure to hold a list of things if not an array?
Lets say you have an object that describes a Person, How would you hold the persons Children?
var kid1 =
{
FirstName: "Abc",
LastName: "Def",
Children: null
};
var kid2 =
{
FirstName: "Abc",
LastName: "Def",
Children: null
};
var dad =
{
FirstName: "Abc",
LastName: "Def",
Children: [kid1,kid2]
};
Children must be an array since a person can have more than one child.

Categories

Resources