making json array in a method - javascript

I am working on an angular application. In my component I have a method as follows:
createPath(node, currentPath = []){
if(node.parent !==null) {
return createPath(node.parent, [node.data.name, ...currentPath])
} else {
return [node.data.name, ...currentPath];
}
}
Here I am recursively calling the method till node.parent becomes null. If it becomes null it will just give me node.data.name. In my each node, I have id also, which I can access using node.data.id. I want to store it in array in following format:
[{
id:1, //can access using node.data.id
name:"myName" //can access using node.data.name. which I am getting in above method.
}
]
This is just example at runtime I can have n number of item, so I want to write a dynamic code which work
in all condition.
I want to modify my above code and make this data in this method only.How can I do that?

Is your array being returned as an array from another destination? Because currently this would work for one item, you should use forEach() and push them into the array, So you will have a new array entry, otherwise the first item will be taken into the list and that will be it.

Did you try this?
createPath(node, currentPath = []){
if(node.parent !== null) {
return createPath(node.parent, [{id: node.data.id, name: node.data.name}, ...currentPath])
} else {
return [{id: node.data.id, name: node.data.name}, ...currentPath];
}
}

Intialiase an array to store your json objects as follows:
array:any=[ ]
Wherever you want to create the array (for example above the return statement of else block) add the following lines:
this.array.push(
{
id: node.data.id,
name: node.data.name
}
)

Related

Loop through 2 Arrays and assign a value from one array into each matching objects of second array

I have 2 Arrays 1.Options and 2.sameAccountArray
options.map((opt, optInd) => {
sameAccountArray.map((acObj, acInd) => {
if (opt.optNumber === acObj.optNumber) {
console.log(opt.optNumber, acObj.optNumber, acObj.exist, acObj.exist, 'WTF', sameAccountArray);
opt.exist = acObj.exist;
} else {
console.log(opt, acObj, opt.optNumber, acObj.optNumber, 'kundi');
// opt.exist = false;
}
// else {
// if (optInd === acInd) {
// opt.exist = acObj.exist;
// } else {
// console.log('elseeee', optInd, acInd,opt.optNumber, acObj.optNumber, opt.exist, acObj.exist);
// }
// }
});
});
Data Structure of sameAccountArray:
{
'key': key,
'shares': this.no_of_shares[key],
'refValue': this.your_reference[key],
'exist': false,
'accountNumber': extractedAccountNumber, 'optNumber': parseInt(extractedOptionNumber)
}
Option have big fields inside, but we don't need to care about it. options and sameAccountArray have common filed named optNumber. I am trying loop through each array and assign a value named exist in each object of the options array if optNumber is same. sameAccountArray already has the correct exist value, I just need to assign that value to match objects of options array. Somehow it's not assigned correctly. Please note that options array and sameAccount Array is not the same length. sameAccountArray has dynamic objects while options have a fixed number of elements. Any idea what is going wrong here guys? Thanks in advance
Try this:
options.forEach(opt=>{
sameAccountArray.forEach(acObj=>{
if (opt.optNumber === acObj.optNumber) opt.exist = acObj.exist;
})
})
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
You cannot modify your arrays with map() function, but only create a new array with the results you want.
let sameAccountObject={};
sameAccountArray.forEach((account)=>{
sameAccountObject[account.optNumber]=account;
});
let result=options.map((option)=>{
let account=sameAccountObject[option.optNumber];
if(account){
option.exist=account.exist;
}
return option;
});
console.log(result);

checking an object property when adding to Array - ES6

I have a simple algorithm problem but couldn't find a proper solution. There is an array and I just want to add an item in the array if the property of recipe_id is not the same in any objects recipe_id property value in the Array.
I want to prevent any item to add if it has the same property value. If the value of the property is different then it is ok. Thus all the objects in the Recipes array should have different recipe_id values. I write these code but it seems it's not working correctly
here is JSBin link : link
const Recipes =[
{recipe_id:4},
{recipe_id:5}
]
onClickedHandler = (recipe_id) => {
const favData = {
recipe_id: recipe_id,
}
if (Recipes.length > 0) {
for (let item in Recipes) {
if (Recipes[item].recipe_id !== recipe_id) {
console.log("added in the loop!")
Recipes.push(item)
} else {
console.log("it is already in the Recipe list!")
}
}
} else {
console.log("Recipes is empty")
Recipes.push({recipe_id:recipe_id})
}
}
onClickedHandler(9)
console.log(Recipes.length)
Use the Array.some method to check if the ID exists in the array.
You probably need something like:
const Recipes =[
{recipe_id:4},
{recipe_id:5}
];
function addRecipe(recipeId) {
if(!Recipes.some(item => item.recipe_id === recipeId)) {
Recipes.push({recipe_id:recipeId});
console.log("Not duplicate, inserted");
} else {
console.log("duplicate");
}
}
addRecipe(4);
addRecipe(6);
console.log(Recipes)
The problem is that you're going through elements, and first item when you're adding an element with id of 4 there is one item with that ID.
It doesn't pass, next iteration, it checks agains the element with different ID. It passes and goes to ID.
You need a loop within a loop, for example try .filter function, if it returns undefined, you can add it, otherwise don't add.
Well you are pushing an object with new recipe whenever you find another object with a different id instead of checking all of them before adding.
if you were to try adding another object with id 7 (onClickedHandler(7)) after all of your code you would end up with 3 different objects with id 7
This happens because you are not returning in your for loop. Of course, it will iterate over all items and, for each item that has different recipe_id, it will append a new item. You should jump out your function once you find the recipe is already there:
for (let item in Recipes) { // Iterate over each item (no need to test length)
if (Recipes[item].recipe_id !== recipe_id) { // Break if recipe already there.
console.log("it is already in the Recipe list!");
return;
}
}
// Otherwise, it is safe to append the recipe_id:
Recipes.push({recipe_id:recipe_id});
console.log("added in the loop!");
Now, when you find the same recipe_id, you exit from your function.

Function to conditionally assign variable member data to nested array in object?

I want to add data into an object, and my object contains nested data. Example data:
pageviewEvent {
client: "clientName",
page {
document_referrer: 'some http refer header data goes here',
window_height: 1920,
window_width: 1200
}
}
Some data is undefined or null and I do not want to add this undefined/null data into the object.
I made a function that works to add data to the object conditionally (if not undefined) but I can't figure out how to add data to nested objects in the function?
I could just make a bunch of if statements, but figure it's better to put the condition test into a function to reduce code size.
Example code with comment showing thinking of what I am trying but doesn't work:
//function to check if variable undefined or null, if not -> add to pageviewEvent arrayKey, variableName
function isUndefinedNull(arrayKey, variableName) {
var evalVariableName = eval(variableName);
if (evalVariableName !== undefined && evalVariableName !== null && evalVariableName !== "") {
console.log(arrayKey);
console.log(variableName);
pageviewEvent[arrayKey] = evalVariableName;
//array key could be nested, for instance pageview[page][title] or pageview.page.tile
}
}
//make event array
const pageviewEvent = { }
//add static data
pageviewEvent.client = 'neguse';
//if not null or undefined add data
isUndefinedNull('referrer.full', 'document.referrer');
//want to put data into object pageviewEvent.referrer.full or pageviewEvent[referrer][full]
Thanks for any help. I feel like this answer can help but I can't figure it out.
I recommend using the lodash function _.set(), documentation can be found here: https://lodash.com/docs/4.17.4#set
_.set( pageviewEvent, "referrer.full", "some-value" );
If you want to customise the behaviour of how nesting is handled when there's an undefined value, you can instead use _.setWith() - see https://lodash.com/docs/4.17.4#setWith

can't get nested forEach to work in Javascript

So I guess the title is selfexplanatory. I have some code with nested forEach loops inside it. The loops are iterating over an array of chapter objects. Each object can have multiple child nodes and they again can have multiple child nodes, and so on.
I want to end up with one array which contains nested arrays with the child nodes.
So far my code looks like this:
exports.chapter = function(req, res) {
var chapters = [],
result = [];
chapters = exports.index(req, res);
chapters.forEach(function(chapter) {
if(chapter.orphan){
result.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
function getChildren(siblings) {
var children = [];
chapters.forEach(function(chapter) {
if($.inArray(chapter, siblings)){
children.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
return children;
};
};
I don't get any errors except for my page not loading. It doesn't write anything in my console. I think it's a problem in the setup but I'm unable to find out where at the moment. Really hope you guys can help.
Most likely problem is here:
if($.inArray(chapter, siblings)){
$.inArray is a horribly misnamed method: It returns an index, or -1 if not found, not a flag as the name implies. -1 is, of course, truthy; and 0 (a valid index), is falsey, so your if probably wants to be
if($.inArray(chapter, siblings) != -1){
// We found it...
}
or possibly
if($.inArray(chapter, siblings) == -1){
// We didn't find it
}
It's a bit strange.. I don't understand why you're using 'add' instead of 'push' method. If I try to "add" an object to an array I get an usual error. Don't you?

Compare Objects in Array and Remove Duplicate & Update - Javascript

I have an array of objects that presents as follows:
0: Object
ConsolidatedItem_catalogId: "080808"
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "Test Catalog Item"
ConsolidatedItem_imageFile: "27617647008728.jpg"
ConsolidatedItem_itemNumber: "1234"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "CAT"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"
1: Object
ConsolidatedItem_catalogId: ""
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "ALARM,SHUTDOWN SYSTEM,AXIOM,XP3, 0-1500 PSIG, HIGH AND LOW PRES Testing"
ConsolidatedItem_imageFile: ""
ConsolidatedItem_itemNumber: "10008"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "INV"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"
I'm trying to update and remove an object if it's added again, or update the object. Preferably update the object with the new value. My code is as follows:
var result = $.grep(finalObject, function(e) {
return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
});
console.log(result);
if (result.length == 0) {
finalObject.push(o);
shoppingCounter = finalObject.length;
$('#numberShoppedItems').text(shoppingCounter);
console.log(finalObject);
} else if (result.length == 1) {
finalObject.filter(function(x){
result = x;
console.log(result);
return x == result.ConsolidatedItem_itemNumber;
});
} else {
alert('Multiples Found');
}
}
I've tried multiple ways of getting the exact object and manipulating the data, however they've all failed. I would prefer to update the object, say if CatalogItem_itemNumber held the same value, if the CatalogItem_quantity was different - add the CatalogItem_quantity values together and update the array of objects.
I don't need an exact answer, a nudge in the right direction would do wonders though. I've looked at several of the related questions over the past couple of hours but none of them seem to address the issue. If you know of a question that has an answer, feel free to just link that as well. I may have missed it.
No Underscore.js please
When you find the matching record, you may update it by using $.extend
$.extend(result[0], o)
This will update the object in finalObject array in-place.
Alternatively, if you want to use the filter, you will need to insert the new object in the array.
finalObject = finalObject.filter(function(x) {
return x !== result[0];
});
finalObject.push(o)
Here we are allowing all the records that are not not equal to result to be returned in the resultant array that is received in finalObject. In next line, we are adding the new record.
Solved in the following manner:
1.) Verify object is not empty.
2.) Use .some() on object to iterate through it.
3.) Check if the finalObject, which is now e, has a match for the key in my temporary object I assemble, o.
4.) Update the values that need updating and return true;
Note: Originally I was going to remove the object by its index and replace it with a new object. This too can work by using .splice() and getting the index of the current object in that array you're in.
Here is the updating version:
if (o.ConsolidatedItem_quantity != '') {
var result = $.grep(finalObject, function(e) {
return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
});
if (result.length == 0) {...}
else {
finalObject.some(function (e) {
if(e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber){
var a;
a = +e.ConsolidatedItem_quantity + +o.ConsolidatedItem_quantity;
e.ConsolidatedItem_quantity = a.toString();
document.getElementById(o.ConsolidatedItem_itemNumber).value=a;
return true;
};
});
}
}

Categories