Related
I have below javascript object - (named Division)
I want to extract only SubDivs from the array
I tried : -
const division = [{
Name: "DivName1",
Value: "DivValue1",
SubDivision: {
Name: "SubDiv1",
Value: "SubDiv1"
}
},
{
Name: "DivName2",
Value: "DivValue2",
SubDivision: [{
Name: "SubDiv2",
Value: "SubDiv2"
},
{
Name: "SubDiv3",
Value: "SubDiv3"
}
]
}
]
var subDivs = division.map(x => x.SubDivision);
console.log(subDivs)
But this is not giving me array in format -
[{
Name:"SubDiv1",
Value:"SubDiv1"
},
{
Name:"SubDiv2",
Value:"SubDiv2"
},
{
Name:"SubDiv3",
Value:"SubDiv3"
}]
You can use flatMap for that
const division = [{
Name: "DivName1",
Value: "DivValue1",
SubDivision: [{
Name: "SubDiv1",
Value: "SubDiv1"
}]
},
{
Name: "DivName2",
Value: "DivValue2",
SubDivision: [{
Name: "SubDiv2",
Value: "SubDiv2"
},
{
Name: "SubDiv3",
Value: "SubDiv3"
}
]
}
]
const subdivision = division.flatMap(d => d.SubDivision)
console.log(subdivision)
Given your example, all you need to do is call flat on the mapped array:
var subDivs= division.map(x=>x.SubDivision).flat();
Working example:
const division = [{
Name: "DivName1",
Value: "DivValue1",
SubDivision: [{
Name: "SubDiv1",
Value: "SubDiv1"
}
]},
{
Name: "DivName2",
Value: "DivValue2",
SubDivision: [{
Name: "SubDiv2",
Value: "SubDiv2"
},
{
Name: "SubDiv3",
Value: "SubDiv3"
}
]
}
]
var subDivs= division.map(x=>x.SubDivision).flat();
console.log(subDivs)
i have two arrays.
const department = [
{ id: '1', name: 'department1' },
{ id: '2', name: 'department2' },
];
const models = [
{
id: '23',
name: 'model1',
departments: [{ id: '1', name: 'department1' }],
},
{
id: '54',
name: 'model2',
departments: [
{ id: '1', name: 'department1' },
{ id: '2', name: 'department2' },
],
},
];
i need to render accordions with department names and accordion details with matching models names. My question is how to filter those arrays to get models
We can map through the departments array, and add a models property that equals the models array, but filtered only to the ones that contain a matching department id.
const departments = [
{ id: "1", name: "department1" },
{ id: "2", name: "department2" },
];
const models = [
{
id: "23",
name: "model1",
departments: [{ id: "1", name: "department1" }],
},
{
id: "54",
name: "model2",
departments: [
{ id: "1", name: "department1" },
{ id: "2", name: "department2" },
],
},
];
const getDepartmentsWithModels = () => {
return departments.map((department) => {
return {
...department,
models: models.filter((model) => {
const modelDepartmentIds = model.departments.map(({ id }) => id);
return modelDepartmentIds.includes(department.id);
}),
};
});
};
console.log(getDepartmentsWithModels());
// [ { id: '1', name: 'department1', models: [ [Object], [Object] ] },
// { id: '2', name: 'department2', models: [ [Object] ] } ]```
I've built some code, which iterates over the departments. For each department it iterates the models and for each model it checks if the department is within the model departments.
const department =
[
{ id: '1', name: 'department1' },
{ id: '2', name: 'department2' }
]
const models =
[
{
id: '23',
name: 'model1',
departments: [{ id: '1', name: 'department1' }]
},
{
id: '54',
name: 'model2',
departments: [{ id: '1', name: 'department1' },{ id: '2', name: 'department2' }]
}
]
department.forEach( dep => {
console.log(`Department: ${dep.name}`)
models.forEach(model => {
if (model.departments.find(modelDep => dep.id===modelDep.id)) {
console.log(` Model: ${model.name}`)
}
})
})
If you could change your data objects, then your code could be much smoother.
I've changed your data objects slightly by just reducing the departments in a model to be an array of department id's. This code iterates over the departments. For each department it filters the models and iterates over the filtered models to output them to the console. This is lesser code and provides much better performance.
const department =
[
{ id: '1', name: 'department1' },
{ id: '2', name: 'department2' }
]
const models =
[
{
id: '23',
name: 'model1',
departments: ['1']
},
{
id: '54',
name: 'model2',
departments: ['1', '2']
}
]
department.forEach( dep => {
console.log(`Department: ${dep.name}`)
models.filter(model => model.departments.includes(dep.id)).forEach(model => {
console.log(` Model: ${model.name}`)
})
})
There are two solutions.
Using Array.reduce() --> returns an object where the key is department name and value is an array of the names of matching models:
let data1 = models.reduce((res, curr) => {
curr.departments.forEach(dep => {
if (!res[dep.name]) {
res[dep.name] = [curr.name]
} else {
if (!res[dep.name].includes(curr.name)) {
res[dep.name].push(curr.name);
}
}
})
return res;
}, {});
Using map and filter --> returns an array of kind:
[{department: [names of the models]},...]
let data2 = department.map(dep => {
let matchingModels = models.filter(model => {
return model.departments.filter(modDep => {
return modDep.name === dep.name;
}).length > 0;
}).map(mod => {
return mod.name;
});
return {
department: dep.name,
models: matchingModels
}
});
I'm reading the environment variables (Key & Value) dynamically and forming below array:
commands: [
{
name: 'PRODUCT_NAME',
value: 'iPhone'
},
{
name: 'PRODUCT_PRICE',
value: '1232'
},
{
name: 'PRODUCT_TYPE',
value: 'Electronics'
},
{
name: 'PRODUCT_ID',
value: 'SKU29389438'
},
{
name: 'LOG_ENABLED',
value: 'TRUE'
},
]
I want to update the key name for these two properties dynamically PRODUCT_TYPE -> myapp.property.type.event and PRODUCT_ID -> myapp.property.product.enabled
Final output should look like this:
commands: [
{
name: 'PRODUCT_NAME',
value: 'iPhone'
},
{
name: 'PRODUCT_PRICE',
value: '1232'
},
{
name: 'myapp.property.type.event',
value: 'Electronics'
},
{
name: 'myapp.property.product.enabled',
value: 'SKU29389438'
},
{
name: 'LOG_ENABLED',
value: 'TRUE'
},
]
Please find my product.js code below:
const commands = (Object.entries(process.env).map(([key, value]) => ({ name: key, value })))
console.log("commands : ", commands);
I'm new to Nodejs, can someone please help how can I update these two key dynamically and form the final array?
Your help would be greatly appreciated!
1) You can just loop over and change the name as:
const obj = {
commands: [
{
name: "PRODUCT_NAME",
value: "iPhone",
},
{
name: "PRODUCT_PRICE",
value: "1232",
},
{
name: "PRODUCT_TYPE",
value: "Electronics",
},
{
name: "PRODUCT_ID",
value: "SKU29389438",
},
{
name: "LOG_ENABLED",
value: "TRUE",
},
],
};
obj.commands.forEach((o) => {
if (o.name === "PRODUCT_TYPE") o.name = "myapp.property.type.event";
if (o.name === "PRODUCT_ID") o.name = "myapp.property.product.enabled";
});
console.log(obj.commands);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
2) You can also do as :
one-liner
obj.commands.forEach((o) => (o.name = changes[o.name] ?? o.name));
const obj = {
commands: [{
name: "PRODUCT_NAME",
value: "iPhone",
},
{
name: "PRODUCT_PRICE",
value: "1232",
},
{
name: "PRODUCT_TYPE",
value: "Electronics",
},
{
name: "PRODUCT_ID",
value: "SKU29389438",
},
{
name: "LOG_ENABLED",
value: "TRUE",
},
],
};
const changes = {
PRODUCT_TYPE: "myapp.property.type.event",
PRODUCT_ID: "myapp.property.product.enabled",
};
obj.commands.forEach((o) => {
if (changes[o.name]) o.name = changes[o.name];
});
console.log(obj.commands);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have a array of object which has a inside array which need to be filtered and return array based on matches from both. search is (input) event, which executes on every key press.
stackblitz link stackblitz
list = [
{
id: 'abc',
data: [
{ key: '1', value: 'car' },
{ key: '2', value: 'bus' },
{ key: '3', value: 'bike' },
{ key: '4', value: 'truck' },
{ key: '5', value: 'jeep' },
],
},
{
id: 'def',
data: [
{ key: '1', value: 'car' },
{ key: '2', value: 'bicycle' },
{ key: '3', value: 'train' },
{ key: '4', value: 'aeroplane' },
{ key: '5', value: 'jeep' },
],
},
];
handleSearch = (event) => {
if (event.target.value.length > 0) {
const item = this.list[0].data.filter((items) =>
items.value.toLowerCase().includes(event.target.value.toLowerCase())
);
this.list[0].data = item;
} else {
this.list[0].data = this.orgList;
}
};
expect output
input = car
output = [
{
id: 'abc',
data: [
{ key: '1', value: 'car' },
],
},
{
id: 'def',
data: [
{ key: '1', value: 'car' },
],
},
];
input = truck
output =
[
{
id: 'abc',
data: [
{ key: '4', value: 'truck' },
],
},
];
const list = [{id: 'abc',data: [{ key: '1', value: 'car' },{ key: '2', value: 'bus' },{ key: '3', value: 'bike' },{ key: '4', value: 'truck' },{ key: '5', value: 'jeep' },],},{id: 'def',data: [{ key: '1', value: 'car' },{ key: '2', value: 'bicycle' },{ key: '3', value: 'train' },{ key: '4', value: 'aeroplane' },{ key: '5', value: 'jeep' },],},];
function search(arr, searchVal) {
return arr.map((item) => {
const data = item.data.filter(({ value }) => value === searchVal);
return { ...item, data };
})
.filter(({ data }) => data.length);
}
console.log(search(list, 'car'));
console.log(search(list, 'truck'));
.as-console-wrapper { max-height: 100% !important; top: 0 }
Angular demo
I know that I might be going a bit outside of the scope of your requirements here, but I just simply thought that it might be easier to do it like this.
I just thought that it might be somewhat more scalable this way, if you first flatten the structure, because for arguments sake, let's say that you're data structure needs to become more & more complex overtime, IDK, business requirements change. At least if you have some layer of abstraction to manage that, you can then filter on an array of objects quite simply, like I've done below.
Depending on your needs you may not even need to flatten the structure, it's just my opinion & experience states this to be an easier & more maintainable kinda solution to scale. If you're data structure dose evolve with complexity, where there may be nested structures, you could always look at using some clever little recursive function to flatten your structure.
It's worth also noting that I've added some validation to the search function, while it's probably not a requirement, it's not a bad idea to include such logic, where you could update state on your view model. You could include something like a toast notification, stating that the user has provided an invalid search term, you could be making a request to a server to get this data & you could say that there were no results, etc, I think you get the idea?
I hope that's helped & I'm sorry if I've gone a little OTT. 😅
const list = [
{
id: 'abc',
data: [
{ key: '1', value: 'car' },
{ key: '2', value: 'bus' },
{ key: '3', value: 'bike' },
{ key: '4', value: 'truck' },
{ key: '5', value: 'jeep' },
],
},
{
id: 'def',
data: [
{ key: '1', value: 'car' },
{ key: '2', value: 'bicycle' },
{ key: '3', value: 'train' },
{ key: '4', value: 'aeroplane' },
{ key: '5', value: 'jeep' },
],
},
];
const flattenStructure = data => {
return data.reduce((accumulator, item) => {
const items = item.data.reduce((vehicles, vehicle) => {
const modified = { ...vehicle, id: item.id };
return vehicles.concat(modified);
}, []);
return accumulator.concat(items);
}, []);
};
const search = (array, term) => {
const invalidTerm = term == null || typeof term != 'string' || term.replace(/ /g, '') == '';
const invalidArray = array == null || !Array.isArray(array);
if (invalidTerm || invalidArray) {
console.log("Invalid arguments provided.");
return array;
}
return flattenStructure(array).filter(vehicle => {
const match = vehicle.value.toLowerCase() == term.toLowerCase();
const contains = vehicle.value.toLowerCase().indexOf(term.toLowerCase()) > -1;
return match || contains;
});
};
console.log(search(list, 'car'));
console.log(search(list, 'truck'));
Generaly speaking, when dealing with filtering, avoid using same original array to display filtered results in template.
Concerning filtering function, this should do the trick:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
public list: any;
public orgList: any;
public filteredList: any;
ngOnInit() {
this.list = this.orgList = [
{
id: 'abc',
data: [
{ key: '1', value: 'car' },
{ key: '2', value: 'bus' },
{ key: '3', value: 'bike' },
{ key: '4', value: 'truck' },
{ key: '5', value: 'jeep' },
],
},
{
id: 'def',
data: [
{ key: '1', value: 'car' },
{ key: '2', value: 'bicycle' },
{ key: '3', value: 'train' },
{ key: '4', value: 'aeroplane' },
{ key: '5', value: 'jeep' },
],
},
];
}
filterData = (dataItem, term: string) => {
return dataItem.value.toLowerCase().indexOf(term.toLowerCase()) !== -1;
};
handleSearch = (event) => {
if (event.target.value.length === 0) {
this.filteredList = [];
return;
}
const term = event.target.value;
const temp = this.list.filter((fullItem) =>
fullItem.data.filter((dataItem) => this.filterData(dataItem, term))
);
this.filteredList = temp
.map((fullItem) => ({
...fullItem,
data: fullItem.data.filter((dataItem) =>
this.filterData(dataItem, term)
),
}))
.filter((fullItem) => fullItem.data.length > 0);
};
}
I'm currently trying to retrieve a list of metadata stored as an array, inside an object, inside an array. Here's a better explanatory example:
[
{
name: 'test',
metadata: [
{
name: 'Author',
value: 'foo'
},
{
name: 'Creator',
value: 'foo'
}
]
},
{
name: 'otherTest',
metadata: [
{
name: 'Created',
value: 'foo'
},
{
name: 'Date',
value: 'foo'
}
]
},
{
name: 'finalTest'
}
]
Now, my objective is to retrieve a list of metadata (by their name) without redundancy. I think that .map() is the key to success but I can't find how to do it in a short way, actually my code is composed 2 for and 3 if, and I feel dirty to do that.
The expected input is: ['Author', 'Creator', 'Created', 'Date']
I'm developping in Typescript, if that can help for some function.
You can use reduce() and then map() to return array of names.
var data = [{"name":"test","metadata":[{"name":"Author","value":"foo"},{"name":"Creator","value":"foo"}]},{"name":"otherTest","metadata":[{"name":"Created","value":"foo"},{"name":"Date","value":"foo"}]},{"name":"finalTest"}]
var result = [...new Set(data.reduce(function(r, o) {
if (o.metadata) r = r.concat(o.metadata.map(e => e.name))
return r
}, []))];
console.log(result)
You could use Set for unique names.
var data = [{ name: 'test', metadata: [{ name: 'Author', value: 'foo' }, { name: 'Creator', value: 'foo' }] }, { name: 'otherTest', metadata: [{ name: 'Created', value: 'foo' }, { name: 'Date', value: 'foo' }] }, { name: 'finalTest' }],
names = new Set;
data.forEach(a => (a.metadata || []).forEach(m => names.add(m.name)));
console.log([...names]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var data = [{"name":"test","metadata":[{"name":"Author","value":"foo"},{"name":"Creator","value":"foo"}]},{"name":"otherTest","metadata":[{"name":"Created","value":"foo"},{"name":"Date","value":"foo"}]},{"name":"finalTest"}]
data
.filter(function(obj){return obj.metadata != undefined})
.map(function(obj){return obj.metadata})
.reduce(function(a,b){return a.concat(b)},[])
.map(function(obj){return obj.name})
A hand to hand Array.prototype.reduce() and Array.prototype.map() should do it as follows;
var arr = [
{
name: 'test',
metadata: [
{
name: 'Author',
value: 'foo'
},
{
name: 'Creator',
value: 'foo'
}
]
},
{
name: 'otherTest',
metadata: [
{
name: 'Created',
value: 'foo'
},
{
name: 'Date',
value: 'foo'
}
]
},
{
name: 'finalTest'
}
];
result = arr.reduce((p,c) => c.metadata ? p.concat(c.metadata.map(e => e.name))
: p, []);
console.log(result);