Why can't I produce unique objects array in this snippet? - javascript

I have the following code snippet, where I want original array (filters) to be filtered and get unique filters array.
I think I tried all the methods possible and it (uniqueFilters array) is still same 11 member original array.
Whats wrong?
How can I ensure that this array is actually filtered down to just a few unique elements in it? (they all are coming from the same place and are the same)
UPDATE:
- the answer successfully resolved the issue in js code.
- in the actual app I had to also deal with typescript to use the suggested answer. So maybe will help someone:
let newUniqueFilters = Array.from(new Map(filters.map(f => [f._id, f] as [string, any])).values());
var filters = [{
"_id": "filter1",
"filterIndex": 1,
"filterLabel": "Blur",
"filterURL": "url(#filter1)",
"filterEffects": [{
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 5
}]
}]
}, {
"_id": "filter2",
"filterIndex": 2,
"filterLabel": "Shadow",
"filterURL": "url(#filter2)",
"filterEffects": [{
"name": "feOffset",
"attributes": [{
"name": "dx",
"value": 20
}, {
"name": "dy",
"value": 20
}, {
"name": "result",
"value": "offOut"
}, {
"name": "in",
"value": "SourceAlpha"
}]
}, {
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 7
}, {
"name": "in",
"value": "offOut"
}, {
"name": "result",
"value": "blurOut"
}]
}, {
"name": "feBlend",
"attributes": [{
"name": "mode",
"value": "normal"
}, {
"name": "in2",
"value": "blurOut"
}, {
"name": "in",
"value": "SourceGraphic"
}]
}]
}, {
"_id": "filter2",
"filterIndex": 2,
"filterLabel": "Shadow",
"filterURL": "url(#filter2)",
"filterEffects": [{
"name": "feOffset",
"attributes": [{
"name": "dx",
"value": 20
}, {
"name": "dy",
"value": 20
}, {
"name": "result",
"value": "offOut"
}, {
"name": "in",
"value": "SourceAlpha"
}]
}, {
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 7
}, {
"name": "in",
"value": "offOut"
}, {
"name": "result",
"value": "blurOut"
}]
}, {
"name": "feBlend",
"attributes": [{
"name": "mode",
"value": "normal"
}, {
"name": "in2",
"value": "blurOut"
}, {
"name": "in",
"value": "SourceGraphic"
}]
}]
}, {
"_id": "filter1",
"filterIndex": 1,
"filterLabel": "Blur",
"filterURL": "url(#filter1)",
"filterEffects": [{
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 5
}]
}]
}, {
"_id": "filter1",
"filterIndex": 1,
"filterLabel": "Blur",
"filterURL": "url(#filter1)",
"filterEffects": [{
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 5
}]
}]
}, {
"_id": "filter1",
"filterIndex": 1,
"filterLabel": "Blur",
"filterURL": "url(#filter1)",
"filterEffects": [{
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 5
}]
}]
}, {
"_id": "filter2",
"filterIndex": 2,
"filterLabel": "Shadow",
"filterURL": "url(#filter2)",
"filterEffects": [{
"name": "feOffset",
"attributes": [{
"name": "dx",
"value": 20
}, {
"name": "dy",
"value": 20
}, {
"name": "result",
"value": "offOut"
}, {
"name": "in",
"value": "SourceAlpha"
}]
}, {
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 7
}, {
"name": "in",
"value": "offOut"
}, {
"name": "result",
"value": "blurOut"
}]
}, {
"name": "feBlend",
"attributes": [{
"name": "mode",
"value": "normal"
}, {
"name": "in2",
"value": "blurOut"
}, {
"name": "in",
"value": "SourceGraphic"
}]
}]
}, {
"_id": "filter1",
"filterIndex": 1,
"filterLabel": "Blur",
"filterURL": "url(#filter1)",
"filterEffects": [{
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 5
}]
}]
}, {
"_id": "filter2",
"filterIndex": 2,
"filterLabel": "Shadow",
"filterURL": "url(#filter2)",
"filterEffects": [{
"name": "feOffset",
"attributes": [{
"name": "dx",
"value": 20
}, {
"name": "dy",
"value": 20
}, {
"name": "result",
"value": "offOut"
}, {
"name": "in",
"value": "SourceAlpha"
}]
}, {
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 7
}, {
"name": "in",
"value": "offOut"
}, {
"name": "result",
"value": "blurOut"
}]
}, {
"name": "feBlend",
"attributes": [{
"name": "mode",
"value": "normal"
}, {
"name": "in2",
"value": "blurOut"
}, {
"name": "in",
"value": "SourceGraphic"
}]
}]
}, {
"_id": "filter1",
"filterIndex": 1,
"filterLabel": "Blur",
"filterURL": "url(#filter1)",
"filterEffects": [{
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 5
}]
}]
}, {
"_id": "filter2",
"filterIndex": 2,
"filterLabel": "Shadow",
"filterURL": "url(#filter2)",
"filterEffects": [{
"name": "feOffset",
"attributes": [{
"name": "dx",
"value": 20
}, {
"name": "dy",
"value": 20
}, {
"name": "result",
"value": "offOut"
}, {
"name": "in",
"value": "SourceAlpha"
}]
}, {
"name": "feGaussianBlur",
"attributes": [{
"name": "stdDeviation",
"value": 7
}, {
"name": "in",
"value": "offOut"
}, {
"name": "result",
"value": "blurOut"
}]
}, {
"name": "feBlend",
"attributes": [{
"name": "mode",
"value": "normal"
}, {
"name": "in2",
"value": "blurOut"
}, {
"name": "in",
"value": "SourceGraphic"
}]
}]
}]
// first method:
var uniqueFilters = [];
for(let i = 0; i < filters.length; i++) {
if(uniqueFilters.indexOf(filters[i]) == -1){
uniqueFilters.push(filters[i])
}
}
console.log("first method")
console.log("original array length:" + filters.length)
console.log("unique array length:" + uniqueFilters.length)
// second method:
//var uniqueFilters = filters.filter(function(elem, index, self) {
// return index == self.indexOf(elem);
//});
//console.log("second method")
//console.log("original array length:" + filters.length)
//console.log("unique array length:" + uniqueFilters.length)
// suggested method 1:
var newUniqueFilters = Array.from(new Map(filters.map(f => [f._id, f])).values());
console.log(newUniqueFilters)

You can use a Map:
filters = Array.from(new Map(filters.map(f => [f._id, f])).values());
This assumes that it is enough to compare the _id values, which uniquely identify filters.
Note that comparing objects themselves (with indexOf or similar methods) will never show duplicates, as all the objects are different references (copies), even though they look the same. In general {} === {} is always false.

It's not working because every element in filter array has different memory location and object are compared by the memory location.
So every time you compare that object exist of filter array in uniqueFilters, it simply doesn't exist because every object has different memory location.
so it will push every element in uniqueFilters.

Try changing this line
if(uniqueFilters.indexOf(filters[i]) == -1){
to
if(uniqueFilters.indexOf(filters[i]) === -1){
If not worikingn you can too try comparing a specific attibute to all uniqueFilter

Related

How to get the absolute path from object using a recursive function?

I am converting the object to tree node format using the below method
function getNodes(object) {
return Object
.entries(object)
.map(([key, value]) => value && typeof value === 'object' ?
{
value: key + value,
label: key,
children: getNodes(value)
} :
{
value: key + value,
label: key
}
);
}
The sample object is:
var object = {
"income-array": [{
"income": {
"id": "1234",
"currency": "dollar",
"details": {
"individual-income": [{
"name": "abcd",
"income": 100
}, {
"name": "xyz",
"income": 500
}]
}
}
}]
}
I am getting this result:
[{
"value": "income-array[object Object]",
"label": "income-array",
"children": [{
"value": "0[object Object]",
"label": "0",
"children": [{
"value": "income[object Object]",
"label": "income",
"children": [{
"value": "id1234",
"label": "id"
}, {
"value": "currencydollar",
"label": "currency"
}, {
"value": "details[object Object]",
"label": "details",
"children": [{
"value": "individual-income[object Object],[object Object]",
"label": "individual-income",
"children": [{
"value": "0[object Object]",
"label": "0",
"children": [{
"value": "nameabcd",
"label": "name"
}, {
"value": "income100",
"label": "income"
}]
}, {
"value": "1[object Object]",
"label": "1",
"children": [{
"value": "namexyz",
"label": "name"
}, {
"value": "income500",
"label": "income"
}]
}]
}]
}]
}]
}]
}]
I want to get the value property path from root to a particular node like the below. I am confused with how to append step by step path to value.
[{
"value": "income-array",
"label": "income-array",
"children": [{
"value": "['income-array'][0]",
"label": "0",
"children": [{
"value": "['income-array'][0]['income']",
"label": "income",
"children": [{
"value": "['income-array'][0]['income']['id']",
"label": "id"
}, {
"value": "['income-array'][0]['income']['currencydollar']",
"label": "currency"
}, {
"value": "['income-array'][0]['income']['details']",
"label": "details",
"children": [{
"value": "['income-array'][0]['income']['details']['individual-income']",
"label": "individual-income",
"children": [{
"value": "['income-array'][0]['income']['details']['individual-income'][0]",
"label": "0",
"children": [{
"value": "['income-array'][0]['income']['details']['individual-income'][0]['name']",
"label": "name"
}, {
"value": "['income-array'][0]['income']['details']['individual-income'][0]['income']",
"label": "income"
}]
}, {
"value": "['income-array'][0]['income']['details']['individual-income'][1]",
"label": "1",
"children": [{
"value": "['income-array'][0]['income']['details']['individual-income'][1]['name']",
"label": "name"
}, {
"value": "['income-array'][0]['income']['details']['individual-income'][1]['income']",
"label": "income"
}]
}]
}]
}]
}]
}]
}]
Can you please guide me how to resolve this? Thanks
The outer function needs to pass its own current absolute path (which is value in your code) to the inner function,
in order to let the inner function know the previous paths.
Notice the parentPath='' parameter and children: getNodes(value, currentPath) below
function getNodes(object, parentPath = "") {
return Object.entries(object).map(([key, value]) => {
const currentPath = parentPath + `[${key}]`;
return value && typeof value === "object"
? {
value: currentPath,
label: key,
children: getNodes(value, currentPath),
}
: {
value: currentPath,
label: key,
};
});
}
After that, run getNodes(object) in the browser and you will get a result like this.
[
{
"value": "[income-array]",
"label": "income-array",
"children": [
{
"value": "[income-array][0]",
"label": "0",
"children": [
{
"value": "[income-array][0][income]",
"label": "income",
"children": [
{
"value": "[income-array][0][income][id]",
"label": "id"
},
{
"value": "[income-array][0][income][currency]",
"label": "currency"
},
{
"value": "[income-array][0][income][details]",
"label": "details",
"children": [
{
"value": "[income-array][0][income][details][individual-income]",
"label": "individual-income",
"children": [
{
"value": "[income-array][0][income][details][individual-income][0]",
"label": "0",
"children": [
{
"value": "[income-array][0][income][details][individual-income][0][name]",
"label": "name"
},
{
"value": "[income-array][0][income][details][individual-income][0][income]",
"label": "income"
}
]
},
{
"value": "[income-array][0][income][details][individual-income][1]",
"label": "1",
"children": [
{
"value": "[income-array][0][income][details][individual-income][1][name]",
"label": "name"
},
{
"value": "[income-array][0][income][details][individual-income][1][income]",
"label": "income"
}
]
}
]
}
]
}
]
}
]
}
]
}
]

react-checkbox-tree doesn't expand

I am new to react. I created a checkbox tree with the react-checkbox-tree package. The problem is when I click on an item in the tree, it doesn't expand when it should.
What changes can I make to fix it
Thanks in advance...
Here sandbox link of the app : sandbox
Here is my JSON database :
[
{
"mailProcessingCenters": [
{
"value": "AEAUHA",
"name": "ABU DHABI"
},
{
"value": "AEDXBA",
"name": "DUBAI"
},
{
"value": "AEDXBB",
"name": "DUBAI RASID SEA-PORT"
},
{
"value": "AEDXBD",
"name": "DUBAI TRANSIT / HUB"
},
{
"value": "AEDXBE",
"name": "DUBAI - SOMALIA"
},
{
"value": "AUSYDK",
"name": "SYDNEY K (EMIRATES - DIRECT LINK)"
},
{
"value": "GBLONO",
"name": "LONDON"
},
{
"value": "SGSINO",
"name": "SINGAPORE"
},
{
"value": "SGSINQ",
"name": "SINGAPORE Q, UAE"
},
{
"value": "USCHIE",
"name": "CHICAGO E"
},
{
"value": "USJECU",
"name": "NEW JERSEY U EMIRATES POST"
}
],
"value": "J1CAEA",
"shortvalue": "AEA",
"label": "EmiratesPost"
},
{
"mailProcessingCenters": [
{
"value": "AFKBLA",
"name": "KABUL"
},
{
"value": "AFKBLC",
"name": "KABUL C"
},
{
"value": "AFKBLS",
"name": "KABUL EMS SHAHEEN POST"
}
],
"value": "J1CAFA",
"shortvalue": "AFA",
"label": "Afghan Post"
},
{
"mailProcessingCenters": [
{
"value": "AGANUA",
"name": "ST JOHNS, A, ANTIGUA AND BARBUDA"
},
{
"value": "AGANUB",
"name": "ST JOHNS, B, ANTIGUA AND BARBUDA"
},
{
"value": "AGANUC",
"name": "ST JOHNS, C, ANTIGUA AND BARBUDA"
}
],
"value": "J1CAGA",
"shortvalue": "AGA",
"label": "GPO Antigua"
},
{
"mailProcessingCenters": [],
"value": "J1CAIA",
"shortvalue": "AIA",
"label": "AnguillaPost"
},
{
"mailProcessingCenters": [
{
"value": "ALTIAA",
"name": "TIRANA ENTRANGER"
}
],
"value": "J1CALA",
"shortvalue": "ALA",
"label": "Albanian PT"
},
{
"mailProcessingCenters": [
{
"value": "AMEVNA",
"name": "YEREVAN"
},
{
"value": "AMEVNB",
"name": "YEREVAN PI-2"
},
{
"value": "AMEVNC",
"name": "YEREVAN PI-3"
},
{
"value": "AMEVND",
"name": "YEREVAN EMS"
}
],
"value": "J1CAMA",
"shortvalue": "AMA",
"label": "Haypost AM"
},
{
"mailProcessingCenters": [],
"value": "J1CANA",
"shortvalue": "ANA",
"label": "POST NA NV"
}
]
And here is my App.js :
class App extends React.Component {
state = {
checked: [],
expanded: [],
database: db
};
render() {
console.log(this.state);
return (
<div>
<div onClick={secildi}>
<CheckboxTree
nodes={this.state.database}
checked={this.state.checked}
expanded={this.state.expanded}
onCheck={checked => this.setState({ checked })}
onExpand={expanded => this.setState({ expanded })}
/>
</div>
<div />
</div>
);
}
}
You have to rename the mailProcessingCenters to children and as suggested by Nicolò Cozzani name should have to be renamed as label.
I can see in the react-checkbox-tree demo, they require the children array to make it a tree which gets expanded.
const nodes = [{
value: 'mars',
label: 'Mars',
children: [ //<--------this one
{ value: 'phobos', label: 'Phobos' }, // <----name should be renamed as label
{ value: 'deimos', label: 'Deimos' },
],
}];
Updated code sand box.

merging the keys inside an object with checking two dimensional arary

how to merge the keys in the array into a single key with using the seperator, if value is null dont take it
let keysToBeMerged = [['note', 'status', seperator: ' ,'], ['group', 'level', seperator: ' ()']];
let data = [
{
"fields": [
{
"key": "area",
"value": null
},
{
"key": "terminal",
"value": null
},
{
"key": "note",
"value": "Some key notes"
},
{
"key": "status",
"value": "Enabled"
},
{
"key": "group",
"value": "Medium"
},
{
"key": "level",
"value": null
}
],
"name": "test 1",
"number": "123456127890",
"id": "yqweyqweu213"
},
{
"fields": [
{
"key": "area",
"value": "Delhi"
},
{
"key": "terminal",
"value": null
},
{
"key": "note",
"value": "Some key orginal notes"
},
{
"key": "status",
"value": "Disabled"
},
{
"key": "group",
"value": "Medium"
},
{
"key": "level",
"value": "High"
}
],
"name": "test 2",
"number": "173276123612",
"id": "uqweyewueyyuqwe"
},
{
"fields": [
{
"key": "area",
"value": "Mumbai"
},
{
"key": "terminal",
"value": 1
},
{
"key": "note",
"value": "Some key orginal sample notes"
},
{
"key": "status",
"value": "Enabled"
},
{
"key": "group",
"value": "Low"
},
{
"key": "level",
"value": null
}
],
"name": "test 3",
"number": "128737812381723",
"id": "kasjdashdkaskjd"
}
]
i have a collection called keysToBeMerged, i need to find the key from the he fields collection and need to merge some keys into a single key with merged values with using the seperator.
tried with below snippet
data.map(o => {
let key = []
let value = []
o.fields.forEach(f => {
keysToBeMerged.forEach(kColl => {
if(kColl.includes(f.key)){
key.push(f.key)
value.push(f.value)
}
})
console.log(key.join(""))
console.log(value.join(""))
})
return o
})
the expectedResult is shown below. Any help appreciated
let expectedResult = [
{
"fields": [
{
"key": "area",
"value": null
},
{
"key": "terminal",
"value": null
},
{
"key": "note|status",
"value": "Some key notes, Enabled"
},
{
"key": "group|level",
"value": "Medium"
}
],
"name": "test 1",
"number": "123456127890",
"id": "yqweyqweu213"
},
{
"fields": [
{
"key": "area",
"value": "Delhi"
},
{
"key": "terminal",
"value": null
},
{
"key": "note|status",
"value": "Some key orginal notes, Disabled"
},
{
"key": "group|level",
"value": "Medium (High)"
},
],
"name": "test 2",
"number": "173276123612",
"id": "uqweyewueyyuqwe"
},
{
"fields": [
{
"key": "area",
"value": "Mumbai"
},
{
"key": "terminal",
"value": 1
},
{
"key": "note|status",
"value": "Some key orginal sample notes, Enabled"
},
{
"key": "group|level",
"value": "Low"
},
],
"name": "test 3",
"number": "128737812381723",
"id": "kasjdashdkaskjd"
}
]

Objects data to be updated with value from Array

I'm trying to update the 'positionTitle' field of my graphData object with the 'positionTitle fields of my individualData array.
I need to do it accurately, both sets of data have 'accounts' which both have the same id and fullname for user, I was hoping to try and use this to do the matching.
I want the positionTitle's from the users with same account id or name (whichever is easier) to go into the objects fields.
This is currently what I have:
My Object (that i want to update):
graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
}
My array whose positionTitles I want to take:
IndividualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
]
The function I'm currently using, which does take the first positiontitle field of the array:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
positionTitle: IndividualData[0].positions[0].positionTitle
}
}))
}))}))
}))
};
console.log(updatedGraphTable)
console.log('a' + JSON.stringify(updatedGraphTable))
my expected result with the positions updated:
updatedGraphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Managing Director"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Managing Director"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
My current result:
{
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
}, {
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334",
"account": {
"id": "eefe"
},
"position": {
"id": "3434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}, {
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
}, {
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34",
"account": {
"id": "3546"
},
"position": {
"id": "3999434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546",
"account": {
"id": "3545"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
Sure, the trick would be to first map your data into an object (so you don't have to search over both arrays all the time), and then conditionally set the value (as I saw that your first manager, doesn't really have a matching position).
So to create the dictionary for usage in your later model, you can first do
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
This would then have an object where accountIdToPositionDict["123"] would be Managing Director, and then change the duplicating logic into:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
Where the position would then be set based on the found accountId in the dictionary, or the original title if no match was found
const individualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
];
const graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
};
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
// then use it in the mapping function
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
console.log( updatedGraphTable );
Try the code below.
accountPositions = {};
IndividualData.forEach((data) => {
accountPositions[data.account.id] = data.positions.filter((pos) => {return pos.isPrimary})[0].positionTitle;
});
graphData.engagementAreas.forEach((area) => {
area.engagementTypes.forEach((type) => {
type.engagements.forEach((engagement) => {
engagement.members.forEach((member) => {
if (!accountPositions[member.account.id]) return;
console.log('position updated from ', member.position.positionTitle, 'to', accountPositions[member.account.id]);
member.position.positionTitle = accountPositions[member.account.id];
});
});
});
});

Nested Loops in angularjs

I have been using nested loops to access data of the json object to display the id and type of topping, however its not working. Here's my code:
var j_obj = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
}, {
"id": "1002",
"type": "Chocolate"
}, {
"id": "1003",
"type": "Blueberry"
}, {
"id": "1004",
"type": "Devil's Food"
}]
},
"topping": [{
"id": "5001",
"type": "None"
}, {
"id": "5002",
"type": "Glazed"
}, {
"id": "5005",
"type": "Sugar"
}, {
"id": "5007",
"type": "Powdered Sugar"
}, {
"id": "5006",
"type": "Chocolate with Sprinkles"
}, {
"id": "5003",
"type": "Chocolate"
}, {
"id": "5004",
"type": "Maple"
}]
}
var Outer_log=[];
debugger
angular.forEach(j_obj, function(an_object){
//Outer_log.push("ID : "+an_object.id+" type : "+an_object.type);
angular.forEach(an_object.topping,function(innerobject){
Outer_log.push("ID : "+innerobject.id+" type : "+innerobject.type);
},Outer_log);
});
console.log(Outer_log);
Could someone please highlight the error in above code, Thanks
Without using nested loop you can iterate using angular.forEach like this
var finalArray=[];
angular.forEach(j_obj[0].topping, function(eachobject){
finalArray.push("ID : "+ eachobject.id+" type : "+ eachobject.type);
});
Angulars forEach is intended to iterate over arrays not object. so if you change your code to something like this
var j_obj = [{ ...}] //object is wrapped inside array.
it will work. Another thing is you don't need a nested loop in this case. You can just do:
angular.forEach(j_obj.topping, function(key, value){ ... });
you are iterating over object where as loop run over array.
hope this helps JSfiddle link
var j_obj = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
}, {
"id": "1002",
"type": "Chocolate"
}, {
"id": "1003",
"type": "Blueberry"
}, {
"id": "1004",
"type": "Devil's Food"
}]
},
"topping": [{
"id": "5001",
"type": "None"
}, {
"id": "5002",
"type": "Glazed"
}, {
"id": "5005",
"type": "Sugar"
}, {
"id": "5007",
"type": "Powdered Sugar"
}, {
"id": "5006",
"type": "Chocolate with Sprinkles"
}, {
"id": "5003",
"type": "Chocolate"
}, {
"id": "5004",
"type": "Maple"
}]
}]
var Outer_log = [];
angular.forEach(j_obj, function(an_object) {
//Outer_log.push("ID : "+an_object.id+" type : "+an_object.type);
angular.forEach(an_object.topping, function(innerobject) {
Outer_log.push("ID : " + innerobject.id + " type : " + innerobject.type);
}, Outer_log);
});
console.log(Outer_log);

Categories