Array javascript filter [duplicate] - javascript

This question already has answers here:
Group array of object nesting some of the keys with specific names
(2 answers)
Closed 2 years ago.
I have an array and i want to filter this array by Country and Service
i did the filter by Country but i want also do the same thing by service
this the array :
[
{
"Country":"CHINA",
"details":"None",
"Service":"BUSINESS",
},
{
"Country":"USA",
"details":"Bus-Trip",
"Service":"BUSINESS",
},
{
"Country":"USA",
"details":"Comm-Trip",
"Service":"COMMUNICATION",
},
];
I was able to do that by this code
let objectData = Data.reduce(function (acc,cur) {
if (!acc[cur.Country])
acc[cur.Country] = { data : []};
acc[cur.Country].data.push(cur)
return acc;
},
{} );
the code above  allowed me to filter only by country and it's work but i want to do this same
thing by country and service BOTH and i want the result like this :
[
{
Country :"CHINA",
Service : [
{"details":"None",}
]
},
{
Country :"USA" ,
Service : [
{"details":"Bus-Trip"},
{"details":"Comm-Trip"}
]
},
]

Some slight modifications to your new object for each country so it reflects what you want and then use Object.values() to get the expected results array
let grouped = Data.reduce(function (acc,{Country, ...rest}) {
acc[Country] = acc[Country] || {Country, Services : []};
acc[Country].Services.push(rest)
return acc;
},{} );
const res = Object.values(grouped)
console.log(res)
<script>
const Data=[{Country:"CHINA",details:"None",Service:"BUSINESS"},{Country:"USA",details:"Bus-Trip",Service:"BUSINESS"},{Country:"USA",details:"Comm-Trip",Service:"COMMUNICATION"}];
</script>

You can try this code.
objectData = Data.reduce(function (acc,cur) {
if (!acc[cur.Country])
acc[cur.Country] = [];
acc[cur.Country].push({details: cur.details});
return acc;
}, {} );
objectData = Object.keys(objectData).map(key => ({
Country: key,
Service: objectData[key]
}));
You first need to modify the reduce code a bit, to contain details data only because you want to strip services.
At this moment, country will be key, so you need one more step to convert objectData to the desired format.
Object.keys(objectData) returns all countries list without duplication, so the second part finally builds the format you require.

Related

Filter an array of objects, by keys in filter object

i'm new here, i have problem that i can not solve.
I have 2 different arrays:
The first array - contains ratings of users with their ID name
[
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
]
The second set - contains the ratings, which I want to return to each user.
If there is a rating that is not in the second set, I will not return it
In the second set, values do not matter, only keys
[
"_assembler",
"_css",
"_python",
"_php"
]
I want to return to the first set, the handle, and all the rankings that exist in the second set.
[
{"handle":"frontend1", "_python":"3" },
{"handle":"frontend3", "_php":"4", "_python":"5" },
{"handle":"frontend4"}
]
this is what i try to do.
keys = [
"_assembler",
"_css",
"_python",
"_php"
]
source = [
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
];
result = [];
tmp = {};
source.forEach((item) => {
Object.keys(item).map(({key,value}) =>
{
if(key == "handle")
{
tmp[key]=value;
}
if(keys.includes(key))
{
tmp[key]=value;
}
})
result.push(...tmp);
tmp = {};
});
You can do this with a map utilizing a couple of other array methods such as filter, and Object methods.
const keys = [
"_assembler",
"_css",
"_python",
"_php"
]
const source = [
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
];
const result = source.map( s => ({
handle: s.handle,
...Object.fromEntries(Object.entries(s).filter(x => x[0] != "handle" && keys.includes(x[0])))
}));
console.log(result);

How to convert JSON Object into key value pair in JS? [closed]

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 2 years ago.
Improve this question
{"1":"val1","2":"val2","3":"val3"}
i want it to converted like this:
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
little Help Please would be much appricated
You can't use the same key name in one object.
instead you can do this.
const origin = {"1":"val1","2":"val2","3":"val3"}
const converted = Object.entries(origin).map( ([key,value]) => ({id: key, value }) );
console.log(converted);
What you have posted is invalid.
What you might want is:
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Object.entries(object));
// or
console.log(Object.keys(object).map(i => ({Id: i, value: object[i]})));
You could use a loop over Object.entries.
E.g. something like:
const newObjArr = [];
for(let [key, value] of Object.entries(obj)){
newObj.push({Id: key, value});
}
The above would return an array of objects, but I'm sure you can amend it to your particular use case.
const data = {"1":"val1","2":"val2","3":"val3"};
const result = Object.keys(data).map((key) => ({ id: key, value: data[key] }));
The result will be [{ id: "1", value: "val1" }, { id: "2", value: "val2" }, { id: "3", value: "val3" }]
As pointed out this is invalis. If you want to convert it if would look like this:
[{"Id":"1","value":"val1"},{"Id":"2","value":"val2"},{"Id":"3","value":"val3"}]
You can make an function that converts this.
const object = {"1":"val1","2":"val2","3":"val3"};
console.log(Convert(object));
function Convert(obj){
return Object.keys(obj).map(i => ({Id: i, value: obj[i]}));
}
You cannot do this. Object is a unique key value pair.
{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
Suppose you want to merge two object and What if both the object has same key, it simply merge the last objects value and have only one key value.
You can convert your large object to several small objects and store them in an array as this snippet shows. (It could be much shorter, but this verbose demo should be easier to understand.)
// Defines a single object with several properties
const originalObject = { "1" : "val1", "2" : "val2", "3" : "val3" }
// Defines an empty array where we can add small objects
const destinationArray = [];
// Object.entries gives us an array of "entries", which are length-2 arrays
const entries = Object.entries(originalObject);
// `for...of` loops through an array
for(let currentEntry of entries){
// Each "entry" is an array with two elements
const theKey = currentEntry[0]; // First element is the key
const theValue = currentEntry[1]; // Second element is the value
// Uses the two elements as values in a new object
const smallObject = { id: theKey, value: theValue };
// Adds the new object to our array
destinationArray.push(smallObject);
} // End of for loop (reiterates if there are more entries)
// Prints completed array of small objects to the browser console
console.log(destinationArray);
const obj = {"1":"val1","2":"val2","3":"val3"}
const newObject = Object.keys(obj).map(e => {
return {ID: e , value : obj[e] }
});
console.log(newObject); // [ { ID: '1', value: 'val1' },
{ ID: '2', value: 'val2' },
{ ID: '3', value: 'val3' } ]
it will give u an array of object, later u need to convert it to object and flat the object:
How do I convert array of Objects into one Object in JavaScript?
how to convert this nested object into a flat object?

Reduce Object Array to Single Object [duplicate]

I've read this answer on SO to try and understand where I'm going wrong, but not quite getting there.
I have this function :
get() {
var result = {};
this.filters.forEach(filter => result[filter.name] = filter.value);
return result;
}
It turns this :
[
{ name: "Some", value: "20160608" }
]
To this :
{ Some: "20160608" }
And I thought, that is exactly what reduce is for, I have an array, and I want one single value at the end of it.
So I thought this :
this.filters.reduce((result, filter) => {
result[filter.name] = filter.value;
return result;
});
But that doesn't produce the correct result.
1) Can I use Reduce here?
2) Why does it not produce the correct result.
From my understanding, the first iteration the result would be an empty object of some description, but it is the array itself.
So how would you go about redefining that on the first iteration - these thoughts provoke the feeling that it isn't right in this situation!
Set initial value as object
this.filters = this.filters.reduce((result, filter) => {
result[filter.name] = filter.value;
return result;
},{});
//-^----------- here
var filters = [{
name: "Some",
value: "20160608"
}];
filters = filters.reduce((result, filter) => {
result[filter.name] = filter.value;
return result;
}, {});
console.log(filters);
var filters = [{
name: "Some",
value: "20160608"
}];
filters = filters.reduce((result, {name, value}= filter) => (result[name] = value, result), {});
console.log(filters);
Since 2019 (ES2019) you can go with Object.fromEntries() but you need to map to array first.
const filtersObject = Object.fromEntries(filters.map(({ name, value }) => [name, value])

JS Object {} advanced filtering

I have a huge chunk of data directly from the database, that data is stored in a JS object : {}, however I'm unable to use built-in JS's .filter function.
Avoid arrow functions as I'm using Vue.JS.
Example of JS Object:
0:
brand: "Brand A"
compatibilitySetIds:Array(3)
createdAt:"2018-08-13T09:07:50.772Z"
deletedAt:null
id:"e7915261-677d-4527-90c6-09b5170afca8"
model:"Model-1"
series:null
type:"A"
updatedAt:"2018-08-13T09:07:50.772Z"
1:
brand: "Brand B"
compatibilitySetIds:Array(3)
createdAt:"2018-08-13T09:07:50.772Z"
deletedAt:null
id:"e7915261-677d-4527-90c6-09b5170afca8"
model:"Model-51"
series:"S02"
type:"B"
updatedAt:"2018-08-13T09:07:50.772Z"
I need to be able to:
Filter by Model
Preferably filter also by Brand/Series/Type
Be able to sort asc/desc in all fields
What I currently have (works)
computed: {
filteredEquipment: function() {
if (this.search.selected === '' || !this.search.selected) {
return this.equipmentItems;
} else {
const model = this.search.selected;
console.log(model);
const filtered = this.equipmentItems.filter(function(item) {
return item.model === model;
});
return filtered;
}
},
},
PS.
Using Vue-JS along with TypeScript.
PPS.
I must filter on the client side, not on the server side.
I'm assuming that your data items are wrapped inside an array, since you have object keys "0" and "1", which seem to be indexes to me. Also you use filter yourself in your code.
You have a couple of choices here to use .filter().
So you can choose which best suites your coding style.
const data = [
{
brand: "Brand A",
compatibilitySetIds: [],
createdAt:"2018-08-13T09:07:50.772Z",
deletedAt:null,
id:"e7915261-677d-4527-90c6-09b5170afca8",
model:"Model-1",
series:null,
type:"A",
updatedAt:"2018-08-13T09:07:50.772Z"
},
{
brand: "Brand B",
compatibilitySetIds: [],
createdAt:"2018-08-13T09:07:50.772Z",
deletedAt:null,
id:"e7915261-677d-4527-90c6-09b5170afca8",
model:"Model-51",
series:"S02",
type:"B",
updatedAt:"2018-08-13T09:07:50.772Z"
}
];
//Specific one liner to filter all Model-1 models.
const AllModel_1Items = data.filter( item => item.model === 'Model-1' );
console.log( AllModel_1Items );
// Generic function with 3 parameters:
const filterProperty = ( source, property, value ) => source.filter( item => item[ property ] === value );
const allTypeA = filterProperty( data, 'type', 'A' );
console.log( allTypeA );
// Generic function usable with .filter()
const byProperty = ( property, value ) => item => item[ property ] === value;
const allBrandA = data.filter( byProperty( 'brand', 'Brand A' ));
console.log( allBrandA );
These functions can filter any property. Sorting asc/desc is just .reverse() the array after .sort().
If for some reason arrows can't be used or filter cannot be used, the same structure can be applied to a simple for loop to mimic .filter().
But since you use both .filter() and arrows in your own code, I'll assume that you can use them.
Object.keys(dbObject) this will convert into array. Then you should be able to use just all the other filter and etc. methods
You can use a loop for read array, and add conditions for filter your data, for example:
let dataFiltered = [];
let data = [
{
brand: "Brand A",
compatibilitySetIds:Array(3),
createdAt:"2018-08-13T09:07:50.772Z",
deletedAt:null,
id:"e7915261-677d-4527-90c6-09b5170afca8",
model:"Model-1",
series:null,
type:"A",
updatedAt:"2018-08-13T09:07:50.772Z",
},
{
brand: "Brand B",
compatibilitySetIds:Array(3),
createdAt:"2018-08-13T09:07:50.772Z",
deletedAt:null,
id:"e7915261-677d-4527-90c6-09b5170afca8",
model:"Model-51",
series:"S02",
type:"B",
updatedAt:"2018-08-13T09:07:50.772Z",
}];
//Use a loop for read array
data.forEach(function(item){
if(item.model === 'Model-1'){
//Add conditions after push item to dataFilter
dataFiltered.push(item);
}
})
console.log(dataFiltered);//In dataFilter is data filtered

JavaScript: Dynamically generated object key [duplicate]

This question already has answers here:
Creating object with dynamic keys [duplicate]
(2 answers)
Closed 5 years ago.
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
]
const output = []
Object.keys(cars).map((car) => {
output.push({
foo: cars[car].defaultCategory
})
})
console.log(output)
This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.
So if I replace push argument with
${cars[car].id}`: cars[car].defaultCategory
I get SyntaxError: Unexpected template string
What am I doing wrong?
Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
];
const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));
console.log(result);
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.
This is how should be your code:
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
var cars = [{
'id': 'truck',
'defaultCategory': 'vehicle'
}];
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
console.log(output);

Categories