angularjs md checkbox get the checked values - javascript

<md-checkbox ng-repeat="primaryPrograms in ctrl.primaryProgramStudies" ng-model="ctrl.primaryProgramStudiesSelected[primaryPrograms.id]">
{{primaryPrograms.name}}
</md-checkbox>
Selected Checbox :
{{ctrl.primaryProgramStudiesSelected | json}}
Output i am getting :
Selected Checbox :
[null,true,true,true,null,true,null,true,null,true,null,null,true]
How can i get the List of Checked Values.

You can filter the original array ctrl.primaryProgramStudies based on whether the same index on ctrl.primaryProgramStudiesSelected has true
var ctrl = {};
ctrl.primaryProgramStudies = [{
"name": "test0",
"id": 0
},
{
"name": "test1",
"id": 1
},
{
"name": "test2",
"id": 2
},
{
"name": "test3",
"id": 3
},
{
"name": "test4",
"id": 4
},
{
"name": "test5",
"id": 5
},
{
"name": "test6",
"id": 6
},
{
"name": "test7",
"id": 7
},
{
"name": "test8",
"id": 8
},
{
"name": "test9",
"id": 9
},
{
"name": "test10",
"id": 10
},
{
"name": "test11",
"id": 11
},
{
"name": "test12",
"id": 12
}
]
ctrl.primaryProgramStudiesSelected = [null, true, true, true, null, true, null, true, null, true, null, null, true]
ctrl.selectedValues = ctrl.primaryProgramStudies.filter(function(obj, index) {
return ctrl.primaryProgramStudiesSelected[index] === true
})
console.log(ctrl.selectedValues)

You can use filter method, which accepts as a parameter a callback method.
The filter() method creates a new array with all elements that pass the test implemented by the provided(callback) function.
var array=[null,true,true,true,null,true,null,true,null,true,null,null,true];
ctrl.primaryProgramStudies.filter(function(item,index){
return array[index]==true;
});
Short example
var ctrl = {};
ctrl.primaryProgramStudies = [{
"name": "program0"
},
{
"name": "program1"
},
{
"name": "program2"
},
{
"name": "program3"
},
{
"name": "program4"
},
{
"name": "program5"
},
{
"name": "program6"
},
{
"name": "program7"
},
{
"name": "program8",
},
{
"name": "program9",
},
{
"name": "program10",
},
{
"name": "program11",
},
{
"name": "program12"
}
]
ctrl.primaryProgramStudiesSelected =[null,true,true,true,null,true,null,true,null,true,null,null,true];
var result=ctrl.primaryProgramStudies.filter(function(item,index){
return ctrl.primaryProgramStudiesSelected[index]==true;
});
console.log(result)

Related

Find user details by ID in nested object nodejs | javascript

How to find name using id. means iterate object. create a function const searchName =()=>{}
suppose if pass 3 in function so I'd want to show .... what the name of user like this
const data = [{
"service": [
"BUSINESS",
"LEGAL",
"FINANCE",
"ADVERTISEMENT"
],
"service1": [
{ "id": 1, "name": "a" },
{ "id": 2, "name": "b" },
{ "id": 3, "name": "c" },
{ "id": 4, "name": "d" },
],
"service2": [
{ "id": 5, "name": "e" },
{ "id": 6, "name": "f" },
{ "id": 7, "name": "g" },
{ "id": 8, "name": "h" },
],
"service3": [
{ "id": 9, "name": "i" },
{ "id": 10, "name": "j" },
{ "id": 11, "name": "k" },
{ "id": 12, "name": "l" },
],
"service4": [
{ "id": 13, "name": "m" },
{ "id": 14, "name": "n" },
{ "id": 15, "name": "o" },
{ "id": 16, "name": "p" },
],
}
]
suppose user pass 3 so I want to return { "id": 3, "name": "c" } like this.
I'm trying to iterate this and find the name of the user by id but I didn't understand this iteration so I need your help.
check this code.... Enter any id number
const data = [{
"service": [
"BUSINESS",
"LEGAL",
"FINANCE",
"ADVERTISEMENT"
],
"service1": [
{ "id": 1, "name": "a" },
{ "id": 2, "name": "b" },
{ "id": 3, "name": "c" },
{ "id": 4, "name": "d" },
],
"service2": [
{ "id": 5, "name": "e" },
{ "id": 6, "name": "f" },
{ "id": 7, "name": "g" },
{ "id": 8, "name": "h" },
],
"service3": [
{ "id": 9, "name": "i" },
{ "id": 10, "name": "j" },
{ "id": 11, "name": "k" },
{ "id": 12, "name": "l" },
],
"service4": [
{ "id": 13, "name": "m" },
{ "id": 14, "name": "n" },
{ "id": 15, "name": "o" },
{ "id": 16, "name": "p" },
],
}]
var itemobj = ''
const searchName =(val)=>{
console.log('searchname')
data.map((item)=>{
let obj = Object.keys(item)
obj.map((data)=>{
let inrdata = item[data]
inrdata.map((initem)=>{
let lastdata = initem.id===val?itemobj=initem:null
})
})
})
}
searchName(3)
console.log(itemobj)
function searchName(id) {
let result = null;
for (const [key, value] of Object.entries(data)) {
if (key === "service") continue
result = value.filter(obj => {
return obj.id === id
})
if (result) break
}
return result ? result[0] : null
}
I iterate through keys, I just skip "service" one since it's not revelant.
Then, I filter the "serviceN" array, it will return an array of object (only one if found, empty array if not found).
If it's found, we stop iterating.
Then we return either the first (and logically only element) or null if not found
You could use a combination of flat and find to get get the user by id
function searchName(id) {
return data
.flatMap((item) => Object.values(item))
.flat()
.find((user) => user.id === id);
}
const result = searchName(3); // { id: 3, name: 'c' } | undefined

Get all parents ids from id list in nested object in javascript

So I have an array of objects which have all nested children property. It is in front-end a treeview, which should expand the nodes until selected ones, for each id in a list. To be able to do this, I have to get all the parents ids for each selected id from the list.
For example, my list of checkedKeys ids:
[16787217, 16787245, 16787266, 16787270, 16787272, 16787265, 16787264]
All the checked items represents the ids from the list object:
My object list looks like this:
[
{
"id": 11,
"name": "Forecast source",
"value": null,
"children": []
},
{
"id": 2,
"name": "Item Type",
"value": null,
"children": []
},
{
"id": 16787217,
"name": "Item#Cust",
"value": null,
"children": [
{
"id": 16787230,
"name": "Customer",
"value": null,
"children": [
{
"id": 16787291,
"name": "Commercial Network",
"value": null,
"children": []
},
{
"id": 16787296,
"name": "Distribution Site",
"value": null,
"children": []
},
{
"id": 16787265,
"name": "Site",
"value": null,
"children": []
}
]
},
{
"id": 16787254,
"name": "Item",
"value": null,
"children": [
{
"id": 16787294,
"name": "ABC (Regular)",
"value": null,
"children": []
},
{
"id": 16787273,
"name": "ABC (U)",
"value": null,
"children": []
},
{
"id": 16787278,
"name": "ABC (€)",
"value": null,
"children": []
},
{
"id": 16787290,
"name": "Class",
"value": null,
"children": []
},
{
"id": 16787260,
"name": "Family",
"value": null,
"children": [
{
"id": 16787264,
"name": "Product line",
"value": null,
"children": []
}
]
},
{
"id": 16787263,
"name": "Flavour",
"value": null,
"children": []
},
{
"id": 16787262,
"name": "Format",
"value": null,
"children": []
},
{
"id": 16787261,
"name": "Group 1",
"value": null,
"children": []
},
{
"id": 16787292,
"name": "ProdGroup",
"value": null,
"children": []
},
{
"id": 16787293,
"name": "Recipe",
"value": null,
"children": []
},
{
"id": 16787288,
"name": "Sale status",
"value": null,
"children": []
}
]
},
{
"id": 16787245,
"name": "Item#Site",
"value": null,
"children": [
{
"id": 16787266,
"name": "Family#Warehouse",
"value": null,
"children": []
}
]
}
]
},
{
"id": 3,
"name": "Lead Time",
"value": null,
"children": []
},
{
"id": 5,
"name": "Levels",
"value": null,
"children": []
},
{
"id": 16787268,
"name": "N1",
"value": null,
"children": [
{
"id": 16787269,
"name": "N2",
"value": null,
"children": [
{
"id": 16787270,
"name": "N3",
"value": null,
"children": [
{
"id": 16787271,
"name": "N4",
"value": null,
"children": [
{
"id": 16787272,
"name": "N5",
"value": null,
"children": [
{
"id": 33564497,
"name": "N6",
"value": null,
"children": [
{
"id": 33564498,
"name": "N7",
"value": null,
"children": [
{
"id": 33564499,
"name": "N8",
"value": null,
"children": [
{
"id": 33564500,
"name": "N9",
"value": null,
"children": []
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
},
{
"id": 16787286,
"name": "Op set",
"value": null,
"children": []
}
]
So my problem is that I can't figure out how to get all parents nodes ids recursively until the root level and push them into the expandedKeys array.
I tried to implement a function like this:
this.list.forEach(el => {
this.setExpandedNodes(el);
});
setExpandedNodes(node: PropertyNode) {
if (node.children) {
node.children.forEach(chld => {
this.checkedKeys.forEach(key => {
if (chld.id === key) {
this.expandedKeys.push(node.id);
} else if (chld.children) {
chld.children.forEach(grChld => {
this.setExpandedNodes(grChld);
});
}
});
});
}
}
But I can't figure out how to get all parent ids starting from each selected id until the root level. Anyone have an idea?
Thanks to this answer I managed to do it.
getPath(model, id) {
let path,
item = model.id ;
if (!model || typeof model !== 'object') {
return;
}
if (model.id === id) {
return [item];
}
(model.children || []).some(child => (path = this.getPath(child, id)));
return path && [item, ...path];
}
setExpandedKeys() {
if (this.checkedKeys && this.checkedKeys.length > 0) {
this.checkedKeys.forEach(k => {
this.list.forEach(
mt => {
const result = this.getPath(mt, k);
if (result) {
this.expandedKeys.push(...result);
}
}
);
});
}
}
this.setExpandedKeys();
I have now all the parents ids until the root.
A function that returns an array of parent objects may look like this:
Using tree-model-js:
const getParentsById = (id, data) => {
var TreeModel = require('tree-model')
const tree = new TreeModel()
let path
for (let item of data) {
const root = tree.parse(item)
root.walk(function (node) {
// Halt the traversal by returning false
if (node.model.id === id) {
path = node.getPath()
return false;
}
});
}
path.pop()
return path.map(item => item.model)
}
Without using tree-model-js:
const getParentsById = (id, data) => {
const isFoundChild = (id, data, parents) => {
if (data.find(item => item.id == id)) {
return true;
}
else {
for (let item of data) {
if (item.children.length)
if (isFoundChild(id, item.children)) {
parents.push(item);
return true;
}
}
return false;
}
}
const parents = [];
if (data.find(item => item.id == id))
return [];
else {
for (let item of data) {
if (item.children.length)
if (isFoundChild(id, item.children, parents)) {
parents.push(item);
return parents;
}
}
}
}
Next, it is enough to apply map() to the result:
let parentsId = getParentsById(16787296, data).map(item => item.id)

Reduce it array to an easier way to map

I'm developing an application and have added new items to my array: type and description.
array = [
{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item1",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item1",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
},
]
I previously did this to reduce it down to an easier way to map it:
items = array.reduce((acc, e) => {
if (!acc[e["item"]["name"]]) {
acc[e["item"]["name"]] = {
[e["date"]["name"]]: e["price"]
}
} else {
acc[e["item"]["name"]][e["date"]["name"]] = e["price"]
}
return acc
}, {})
To show the data before I did
const dates = [...new Set(Object.keys(items_dicc).map(i => Object.keys(items_dicc[i])).flat())]
{
Object.keys(items_dicc).map((item) => {
return (
<tr>
<td>{item}</td>
{dates.map((date) => <td>{items_dicc[item][date] || ''}</td>)}
</tr>
)
})
}
I need to add the description element and type.name to the above. For example for description:
description: e["description"]
To display the elements as in the table:
ITEM
DESCRIPTION
TYPE
202001
202002
I1
item1
type1
100
200
I2
item3
type2
-
300
How do I add and show?
EDIT: console.log(items_dicc[item])
{202001: 100, 202002: 200, description: "item1", type: "type1"}
202001: 100
202002: 200
description: "item1"
type: "type1"
__proto__: Object
{202002: 300, description: "item3", type: "type2"}
202002: 300
description: "item3"
type: "type2"
__proto__: Object
You can add the description and type attribute inside the reduce method like this,
array = [
{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item2",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item3",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
},
]
items = array.reduce((acc, e) => {
if (!acc[e["item"]["name"]]) {
acc[e["item"]["name"]] = {
[e["date"]["name"]]: e["price"],
'description': e['description'],
'type': e.type?.name,
}
} else {
acc[e["item"]["name"]][e["date"]["name"]] = e["price"]
}
return acc
}, {})
console.log(items);
To add the for description and name in the table,
const dates = [...new Set(Object.keys(items_dicc).map(i => Object.keys(items_dicc[i])).flat())]
{
Object.keys(items_dicc).map((item) => {
return (
<tr>
<td>{item}</td>
<td>{items_dicc[item]?.description}</td>
<td>{items_dicc[item]?.type}</td>
{dates.map((date) => <td>{items_dicc[item][date] || ''}</td>)}
</tr>
)
})
}
I have been seeing your question regarding these type of tables from yesterday. You have posted several questions with similar things. I suggest you to read some article and understand how JS array methods works instead of asking incremental questions in SO.
Asking in SO might solve your problems for now, but in the long run you will suffer as you don't seem to have a grip on how these things works.
you can simplify your solution like this.
const array = [{
"id": 1,
"description": "item1",
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 100
},
{
"id": 2,
"description": "item2",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"type": {
"id": 1,
"name": "type1"
},
"price": 200
},
{
"id": 3,
"description": "item3",
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"type": {
"id": 2,
"name": "type2"
},
"price": 300
}
]
const result = array.map(item => {
return Object.keys(item).reduce((a, c) => {
if (c === "date") {
a[item[c].name] = item.price;
} else if (c !== "price" && c !== "id") {
a[c] = (typeof item[c] === "object") ? item[c].name : item[c];
}
return a;
}, {})
});
console.log(result);

JSON / JavaScript - find matching values, make them into keys and create new, consolidated object

In vanilla JavaScript, how would I find unique locations from this object and make them keys, and place all items with that location as values. (can install lodash if necessary).
So this:
[
{
"item": {
"id": "cat"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "dog"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "snake"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "bird"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "beer"
},
"location": {
"id": "fridge"
}
}
]
Becomes this:
[
{
"porch": [
{
"id": "cat"
},
{
"id": "dog"
}
]
},
{
"forest": [
{
"id": "snake"
},
{
"id": "bird"
}
]
},
{
"fridge": [
{
"id": "beer"
}
]
}
]
PEN
// modified desired result
[
{
"location": {
"name": "porch",
"items": [
{
"title": "cat"
},
{
"title": "dog"
}
]
}
},
{
"location": {
"name": "forest",
"items": [
{
"title": "snake"
},
{
"title": "bird"
}
]
}
},
{
"location": {
"name": "fridge",
"items": [
{
"title": "beer"
}
]
}
}
]
let obj = [
{
"item": {
"id": "cat"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "dog"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "snake"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "bird"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "beer"
},
"location": {
"id": "fridge"
}
}
]
let result = {};
obj.forEach(({item, location}) => {
if(!result[location.id]) result[location.id] = []
result[location.id].push({title: item.id})
})
result = Object.keys(result).map(key => ({
"location": {
"name": key,
"items": result[key]
}
}))
result contains required output.

JavaScript divide array of objects by field

I have a JSON file like this:
[
{
"type": -1,
"name": "First Group"
},
{
"type": 2,
"name": "A"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
},
{
"type": -1,
"name": "Second Group"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
},
{
"type": -1,
"name": "Third Group"
},
{
"type": 4,
"name": "C"
},
{
"type": 2,
"name": "A"
}
]
And I would like to divide this array of objects on many arrays, and grouping it by "type": -1 field.
For example for current JSON I would like to get something like this:
1)
[
{
"type": -1,
"name": "First Group"
},
{
"type": 2,
"name": "A"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
}
]
2)
[
{
"type": -1,
"name": "Second Group"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
}
]
3)
[
{
"type": -1,
"name": "Third Group"
},
{
"type": 4,
"name": "C"
},
{
"type": 2,
"name": "A"
}
]
My question in the next:
Does it exist some function on TypeScript/JavaScript for doing this? Or need to create something specific. And if doesn't exist then how to create a better and fast solution for this?
const arr = [{"type": -1,"name": "First Group"},{"type": 2,"name": "A"},{"type": 3,"name": "B"},{"type": 4,"name": "C"},{"type": -1,"name": "Second Group"},{"type": 3,"name": "B"},{"type": 4,"name": "C"},{"type": -1,"name": "Third Group"},{"type": 4,"name": "C"},{"type": 2,"name": "A"}];
const chunks = [];
let chunk = [];
arr.forEach((item) => {
if(item.type === -1) {
if(chunk.length) {
chunks.push(chunk);
}
chunk = [];
}
chunk.push(item);
});
chunks.push(chunk);
console.log(chunks);
Just try following simple logic.
var data = [
{
"type": -1,
"name": "First Group"
},
{
"type": 2,
"name": "A"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
},
{
"type": -1,
"name": "Second Group"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
},
{
"type": -1,
"name": "Third Group"
},
{
"type": 4,
"name": "C"
},
{
"type": 2,
"name": "A"
}
];
var output = [],
_index = 0;
data.forEach(function(obj){
if(obj.type == -1){
output.push([obj]);
_index++;
} else {
output[_index-1].push(obj);
}
});
console.log(output);
Use Array.prototype.reduce:
const collection = [{
"type": -1,
"name": "First Group"
},
{
"type": 2,
"name": "A"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
},
{
"type": -1,
"name": "Second Group"
},
{
"type": 3,
"name": "B"
},
{
"type": 4,
"name": "C"
},
{
"type": -1,
"name": "Third Group"
},
{
"type": 4,
"name": "C"
},
{
"type": 2,
"name": "A"
}
]
const makeReducerByTypeValue = value => (result, el, index) => {
if (el.type === value) {
result.sorted.push([])
if (index > 0) result.currentIndex++
}
result.sorted[result.currentIndex].push(el)
return result
}
const sorted = collection.reduce(makeReducerByTypeValue(-1), {
currentIndex: 0,
sorted: []
}).sorted
sorted.forEach(el => console.log(el))
There is no built-in function or method for this to get the wanted groups.
You could take a new array for every found type equals -1 and take for all other types the last inserted array of the result set.
This works obviously only for sorted arrays only.
var array = [{ type: -1, name: "First Group" }, { type: 2, name: "A" }, { type: 3, name: "B" }, { type: 4, name: "C" }, { type: -1, name: "Second Group" }, { type: 3, name: "B" }, { type: 4, name: "C" }, { type: -1, name: "Third Group" }, { type: 4, name: "C" }, { type: 2, name: "A" }],
grouped = array.reduce(function (r, a) {
if (a.type === -1) {
r.push([a]);
} else {
r[r.length - 1].push(a);
}
return r;
}, []);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories