admin管理员组文章数量:1398821
How do I write select distinct country, state from myObject
in javascript.
Array.from(new Set(myObject.map(item => item.country)))
would return distinct countries.. How do I add countries, states and other columns in map???
Input data:
const myObject = [
{
country: 'USA',
state: 'Missouri',
county: 'County1',
},
{
country: 'USA',
state: 'Missouri',
county: 'County2',
},
{
country: 'Canada',
state: 'Alberta',
county: 'County3',
},
];
To get unique countries, I would write Array.from(new Set(myObject.map(item => item.country))) The result would be ['USA', 'Canada']
What should I write if want the result to be
[
{
country: 'USA',
state: 'Missouri',
},
{
country: 'Canada',
state: 'Alberta',
},
]
This contains unique country and state binations
How do I write select distinct country, state from myObject
in javascript.
Array.from(new Set(myObject.map(item => item.country)))
would return distinct countries.. How do I add countries, states and other columns in map???
Input data:
const myObject = [
{
country: 'USA',
state: 'Missouri',
county: 'County1',
},
{
country: 'USA',
state: 'Missouri',
county: 'County2',
},
{
country: 'Canada',
state: 'Alberta',
county: 'County3',
},
];
To get unique countries, I would write Array.from(new Set(myObject.map(item => item.country))) The result would be ['USA', 'Canada']
What should I write if want the result to be
[
{
country: 'USA',
state: 'Missouri',
},
{
country: 'Canada',
state: 'Alberta',
},
]
This contains unique country and state binations
Share Improve this question edited Oct 14, 2020 at 13:18 jcalz 332k29 gold badges442 silver badges442 bronze badges asked Oct 14, 2020 at 1:42 Nikhila Reddy CNikhila Reddy C 591 gold badge2 silver badges8 bronze badges 4- could you provide an example of the input data and the expected result? not sure if this is what you're looking for stackoverflow./questions/56633869/… – diedu Commented Oct 14, 2020 at 1:53
- I edited the question with sample data and expected result. – Nikhila Reddy C Commented Oct 14, 2020 at 2:21
- @diedu I'm not sure why you think this question is not related to TypeScript? – jcalz Commented Oct 14, 2020 at 2:23
- I updated my answer to use your example. If it does not address your use case, please elaborate. – jcalz Commented Oct 14, 2020 at 13:21
3 Answers
Reset to default 2Below is a solution using reduce;
const myObject = [
{ country: 'USA', state: 'Missouri', county: 'County1' },
{ country: 'USA', state: 'Missouri', county: 'County2' },
{ country: 'Canada', state: 'Alberta', county: 'County3' },
];
const unique = myObject.reduce((prev, {country, state}) =>
prev.some(x => x.country === country && x.state === state )? prev: [...prev, {country, state} ], [])
console.log(unique )
Base on referenced answer you can use Map
and spread operator
as below
https://stackoverflow./a/63274702/4964569
const myObject = [
{ country: 'USA', state: 'Missouri', county: 'County1' },
{ country: 'USA', state: 'Missouri', county: 'County2' },
{ country: 'Canada', state: 'Alberta', county: 'County3' },
];
let data = new Map();
for (let obj of myObject) {
delete obj.county;
data.set(obj.country, obj);
}
let unique = [...data.values()];
console.log(unique);
The following code should take an array of objects and a list of keys of those objects, and return an array of objects representing the distinct values for that set of keys. I assume that the type of properties at those keys will only be string
, number
, or boolean
.
function distinct<T extends Record<K, string | number | boolean>,
K extends keyof T>(arr: T[], ...keys: K[]): Pick<T, K>[] {
const key = (obj: T) => JSON.stringify(keys.map(k => obj[k]));
const val = (obj: T) => keys.reduce((a, k) => (a[k] = obj[k], a), {} as Pick<T, K>);
const dict = arr.reduce((a, t) => (a[key(t)] = val(t), a), {} as { [k: string]: Pick<T, K> })
return Object.values(dict);
}
The idea is to take each object in the array, serialize the tuple of its properties at the keys in question with JSON.stringify()
, and use this serialized string as a dictionary key. The value we put at that key is an object consisting of just the values at those properties. By using a dictionary, we guarantee that only one object will appear for each distinct set of properties at the keys we care about. Then we turn the values of this dictionary into an array.
If I test it on your myObject
example, this is what es out:
const result = distinct(myObject, "country", "state");
console.log(result);
/* [{ "country": "USA", "state": "Missouri" }, { "country": "Canada", "state": "Alberta" }] */
which is what you wanted. Let's also test it on some type and array that I made up now:
interface MyObject {
country: string,
state: string,
age: number,
name: string
}
const arr: MyObject[] = [
{ name: "Alice", age: 35, country: "USA", state: "MA" },
{ name: "Bob", age: 40, country: "USA", state: "MI" },
{ name: "Carmen", age: 35, country: "Mexico", state: "BC" },
{ name: "Danilo", age: 35, country: "Mexico", state: "MI" }
]
So we have an array of MyObject
. Let's get the distinct country
values:
const distinctCountries = distinct(arr, "country"); // Array<{country: string}>
console.log(distinctCountries); // [{ "country": "USA" }, { "country": "Mexico" }]
console.log(distinctCountries.map(x => x.country)); // USA, Mexico
Notice how what es out is an array of {country: string}
values. You can use map()
to turn that into just an array of string
s. Let's get the distinct country
and state
values:
const distinctCountriesAndStates = distinct(arr, "country", "state");
console.log(distinctCountriesAndStates);
/* [{ "country": "USA", "state": "MA" }, { "country": "USA", "state": "MI" },
{ "country": "Mexico", "state": "BC" }, { "country": "Mexico", "state": "MI" }] */
Here it's an array of {country: string, state: string}
objects. Not sure how you want to represent those, but you can use map()
to massage them as you see fit. Finally let's get the distinct country
and age
values:
const distinctAgesAndCountries = distinct(arr, "country", "age");
console.log(distinctAgesAndCountries);
/* [{ "country": "USA", "age": 35 }, { "country": "USA", "age": 40 },
{ "country": "Mexico", "age": 35 }] */
That's an array of {country: string, age: number}
objects.
Anyway, hope that gives you some direction.
Playground link to code
本文标签: javascriptTypescript get distinct values from an objectStack Overflow
版权声明:本文标题:javascript - Typescript get distinct values from an object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744090939a2589408.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论