Get index of object that contains value in a nested array - JavaScript - javascript

I've been searching for something to help me on this particular problem but I've not found a suitable solution which works for my case. I'd really appreciate it if somebody could point me in the right direction.
I have an array:
var ruizTreeData = [
{
"Name": "Ruiz Hernandez",
"parent": "null",
"nodetype": "person",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Checking",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Renato Godoy",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Juan Nieto",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Bani Cortes",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
},
{
"Name": "Medina Marquez",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
}
]
}
]
}
];
I have another function which is creating an object, and what I'd like to do is insert that object into this "tree" at a particular index. So for example, the user would choose to insert a new person underneath "Ruiz Hernandez", so I'd create an object which would be a sibling of "Checking". But I want it to be flexible enough so that if somebody added as a child of "Checking" we'd do the same, or a child of "Bani Cortes" we'd do the same etc.
I'm thinking I'd have to iterate ruizTreeData until I found "Ruiz Hernandez" and then insert the object into the children array of "Ruiz Hernandez".
So the array would then look like:
var ruizTreeData = [
{
"Name": "Ruiz Hernandez",
"parent": "null",
"nodetype": "person",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Checking",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Renato Godoy",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
}...
]
},
{
"Name": "Inserted object",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png"
}
]
}
];
I've tried a bunch of things, the closest I've got is:
positionInTree = ruizTreeData
.map(function (element) {return element["Name"];})
.indexOf("Ruiz Hernandez");
But this only returns at the first index, it doesn't go into the nested objects. Would I need a for loop for this?
I'd really appreciate some help with this. Thanks very much.

There you go. You can select your element by a key/value identifier and this function will create a children property if there isn't one already with your object inside it or add your object into the already existing children property.
I added a person named Ruiz Hernandez into the last node (Checking's children) to show you how the function add your object in every node with your key/value identifier.
var ruizTreeData = [
{
"Name": "Ruiz Hernandez",
"parent": "null",
"nodetype": "person",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Checking",
"nodetype": "account",
"Country": "assets/img/aml-flag-1.png",
"children": [
{
"Name": "Renato Godoy",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Juan Nieto",
"nodetype": "person",
"Country": "assets/img/aml-flag-4.png"
},
{
"Name": "Bani Cortes",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
},
{
"Name": "Ruiz Hernandez",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
},
{
"Name": "Medina Marquez",
"nodetype": "person",
"Country": "assets/img/aml-flag-2.png"
}
]
}
]
}
];
Array.prototype.addChild = function(key, value, object){
let el;
if(this.find(x => x[key] == value)){
this.filter(x => x[key] == value).forEach(y => y.children = (y.children) ? [...y.children, {...object}] : [{...object}])
}
this.forEach(y => {
if(y.children){
y.children.addChild(key, value, object);
}
});
}
ruizTreeData.addChild("Name", "Ruiz Hernandez", {Name: "Name"});
console.log(ruizTreeData);

Related

Loop through a JSON object and display items as unordered list

i have a fetch that return a json object like this:
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "name",
"instant_invite": "link",
"channels": [
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Altri Giochi",
"position": 8
},
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Ascolto Musica",
"position": 11
},
],
"members": [
{
"id": "0",
"username": "xxxxxxxxxxxxxx",
"discriminator": "0000",
"avatar": null,
"status": "idle",
"avatar_url": "https://url"
},
],
"presence_count": 3
}
now i'm trying to map and display all these items to make an unordered list for my website, but i can't map this object with this.myResponse.map...i get an error "map is not a function".
i'm definitely lost here and i need some help to make an unordered list that contain all members name, avatar and other stuff.
can someone help me on this in vanilla js?
You can loop through the object using Object.keys(). Here's an example
let data = {
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "name",
"instant_invite": "link",
"channels": [{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Altri Giochi",
"position": 8
},
{
"id": "xxxxxxxxxxxxxxxxxxx2",
"name": "Ascolto Musica",
"position": 11
},
],
"members": [{
"id": "0",
"username": "xxxxxxxxxxxxxx",
"discriminator": "0000",
"avatar": null,
"status": "idle",
"avatar_url": "https://url"
},
{
"id": "1",
"username": "yyyyyyyyyyyyy",
"discriminator": "0000",
"avatar": null,
"status": "idle",
"avatar_url": "https://url"
},],
"presence_count": 3
}
data.members.forEach(m => {
// start the UL
let ul = "<ul class='member'>";
// loop through using Object.keys(m) or preset array of keys
['username','avatar'].forEach(md => {
ul += `<li>${md}: ${m[md]}</li>`;
})
ul += "</ul>";
document.querySelector('#members').innerHTML += ul;
})
<div id='members'></div>

Paasing an object into an array of arrays

Have an object that needs to be pass inside the array of source using javascript,throwing an error spec is undefined when using push function. will push function work for this scenario
var a = [
"name": "ben",
"type": "male",
"appType": "human",
"spec": {
"view": "instanceview",
"sink": {
"source": [{
"data": {
"path": "google/path",
"name": "test",
"Id": "11234",
},
"ref": "www.xyz.com",
"id": "isdfjsbfjsfb",
"resourceType": "app"
}
],
},
},
}]
var b = {
"data": {
"path": "google/path",
"name": "goldengate",
"Id": "11234vndslknvlsmnv",
},
"ref": "www.xyz.com",
"id": "6452367e5375",
"resourceType": "app"
}
a.spec.sink.source.push(b);
would expect b to be pushed to source
An array with string keys is not a valid structure, you need to convert a to an object
var a = { // <-- here
"name": "ben",
"type": "male",
"appType": "human",
"spec": {
"view": "instanceview",
"sink": {
"source": [
{
"data": {
"path": "google/path",
"name": "test",
"Id": "11234",
},
"ref": "www.xyz.com",
"id": "isdfjsbfjsfb",
"resourceType": "app"
}
],
},
},
} // <-- here

Convert nested JSON to flat JSON - In order to insert them as records in SQL

I have a JSON string in nested pattern like below:
NESTED (Just Example):
{
"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" }
]
}
I want an option or way to convert this nested JSON string to a flat JSON string so that I can insert them like a record in SQL table.
Can you please help on how to structure the JSON from nested to flat?

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);

http request and convert to json with comparision of json

I want to make a http request to a url lets say
http://test1.com/info this will give me xml
I want to convert
this xml from 1 to json lets say json 1
Now I make a rest request to url lets
say http://test2.com/myweb this returns a json lets say json 2
json 1
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7"
}
.... some 100 entries
]
and json 2 some like below
[
{
"id": "123",
"country": "USA",
"state": "KA",
"age": 24,
"group": "g1"
}
{
"id": "456",
"country": "UK",
"state": "MA",
"age": 28,
"group": "G2"
}
...... 100 entries
]
Now Id is the constant thing between json1 and json2 I want to make a resultant json something like below lets call json3.I want to match the id and get country and state from json2 and append to json1
[
{
"id": "123",
"testname": "test123",
"name": "John Doe",
"active": true,
"type": "test6",
"country":"USA",
"state":"KA"
}
{
"id": "456",
"testname": "test564",
"name": "Ship Therasus",
"active": true,
"type": "test7",
"country":"UK",
"state":"MA"
}
]
Now wat i tried for 1 and 3 but for 2 dont know wat to do and to compare and combine I am not sure wat to do If any help will be greatful
function fun()
{
var data="hello";
$.post('http://localhost/ws/service.asmx/HelloWord',{},function(response)
{ data = response;
}).error(function(){
alert("Sorry could not proceed");
});
return data;
}
you can try this:
<script>
$(document).ready(function(){
var result=[];
var x=[{"id": "123","testname": "test123", "name": "John Doe","active": true,"type": "test6"},{"id": "456", "testname": "test564", "name": "Ship Therasus", "active": true,"type": "test7" }];
var y = [{ "id": "123", "country": "USA", "state": "KA", "age": 24,"group": "g1"},{ "id": "456", "country": "UK", "state": "MA", "age": 28, "group": "G2"}];
for (i in x){
for (j in y){
if(x[i].id == y[j].id){
result.push($.extend(x[i], y[j]));
}
}
}
console.log(result);
});
</script>

Categories