Having trouble reading data from an object - javascript

I don't understand how to read the genre data.
"data":
"genres": [
{
"id": 0,
"type": "string",
"name": "string",
"url": "string"
},
{
"id": 1,
"type": "string",
"name": "string",
"url": "string"
}
],
}
I want it to end up being displayed like
name1, name2, name3
and (if possible) I want to have each of the names have the link to their corresponding url.
I have tried to find that data by
var genres = data.genres;
But that just returns [object Object],[object Object]
Im guessing that you have to read the data from those objects, but I don't know how to.

What you need to understand from that is the following: "data" is an object and it has a "genres" property which has an array of objects inside it. Knowing this you can just do the following:
const name1 = data.genres[0].name; // Gets the first name
const name2 = data.genres[1].name; // Gets the second name
If you want to loop through the genre data, then you need to iterate through the objects inside the "genres" property:
data.genres.map((genre) => console.log(genre.name)); // Logs all names
This would be a more common example:
for (let i = 0; i < data.genres.length; i++) {
const name = data.genres[i].name;
console.log(name); // Logging the names
}

You'll have to loop to go through the data, and create a-elements to create a link. You'll also need a parent element to append the links to:
const yourParentElement = document.getElementById("parent");
var genres = data.genres;
genres.forEach(genre => {
var lnkGenre = document.createElement("a");
lnkGenre.textContent = genre.name;
lnkGenre.href = genre.url;
You can also add classes or an id here:
lnkGenre.classList.add("yourClass");
lnkGenre.id = genre.id;
yourParentElement.appendChild(lnkGenre);
});

Related

how to iterate parent to child objects and pushed into an array javascript (vuejs)

I have json data like this.
var obj= {
"id": "6",
"name": "parent",
"path": "/",
"category": "folder",
"fid":"6"
"children": [
{
//some values
},
{
//some other values
}
]
}
how to iterate and push it into an new array.
type declaration
getEntry: Array<Object> = []
pushing into an array method
get addedEntry() {
let files = []
this.getEntry = files.push(this.obj)
}
But, i am getting type error. How to push this object into an array or make it array.?
The push method returns a Number representing the new value of the array. That's why you are getting a TypeError (you are assigning a Number to an Array of Objects).
You should do the following instead.
get addedEntry() {
let files = []
files.push(this.obj)
this.getEntry = files
}
Here's the docs entry for the push method in JavaScript.

Javascript - how to loop through dict inside a list

So I am pretty new when it comes to Javascript and it is as simple as read a json list with a value of:
{
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
What I would like to do is to have both the URL and the amount of numbers etc
"https://testing.com/en/p/-12332423/" and "999"
and I would like to for loop so it runs each "site" one by one so the first loop should be
"https://testing.com/en/p/-12332423/" and "999"
second loop should be:
"https://testing.com/en/p/-123456/" and "123"
and so on depending on whats inside the json basically.
So my question is how am I able to loop it so I can use those values for each loop?
As Adam Orlov pointed out in the coment, Object.entries() can be very useful here.
const URLobj = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
};
URLobj.URL.forEach(ob => {
console.log('ob', ob);
const entries = Object.entries(ob)[0]; // 0 just means the first key-value pair, but because each object has only one we can just use the first one
const url = entries[0];
const number = entries[1];
console.log('url', url);
console.log('number', number);
})
You mean something like this using Object.entries
const data = {
"URL": [
{"https://testing.com/en/p/-12332423/": "999"},
{"https://testing.com/en/p/-123456/": "123"},
{"https://testing.com/en/p/-456436346/": "422"}
]
}
data.URL.forEach(obj => { // loop
const [url, num] = Object.entries(obj)[0]; // grab the key and value from each entry - note the [0]
console.log("Url",url,"Number", num); // do something with them
})
let's call your object o1 for simplicity. So you can really go to town with this link - https://zellwk.com/blog/looping-through-js-objects/
or you can just use this code :
for(var i = 0; i < o1.URL.length; i++) {
//each entry
var site = Object.keys(URL[i]) [0];
var value = Object.values(URL[i]) [0];
// ... do whatever
}
don't forget each member of the array is an object (key : value) in its own right
You can extract the keys and their values into another object array using map
Then use the for loop on the newly created array. You can use this method on any object to separate their keys and values into another object array.
const data = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
var extracted = data.URL.map(e => ({
url: Object.keys(e)[0],
number: Object.values(e)[0]
}))
extracted.forEach((e) => console.log(e))

Is there an efficient way to iterate through an avro schema?

I would like to be able to iterate through and access the 'name' field values of an avro schema but have not been able to find an efficient way of doing so without getting extra values due to the particular way avro expects its schema data.
I can recursively iterate through it as though it were a js object; however, I end up with certain fields I did not want being included in my results.
For example, in the below code the only value I want to get back is 'foobar' however I also get 'Foo' which I do not want as that is the name of an array of objects rather than a single value.
{
"type": "record",
"name": "Foo",
"fields": [
{
"name": "foobar",
"type": "string"
}
]
}
The current function I am using looks like this:
iterateAvro = (target) => {
let result = [];
Object.entries(target).forEach(([key, val]) => {
if (val === null){
return null
}
if (typeof val === 'object'){
result = result.concat(this.iterateAvro(val));
} else {
if(key === 'name'){
result.push(val)
}
}
})
return result
}
I am new to avro (and coding in general) and do not know if there is an avro specific way of doing this. Any help would be appreciated.
What you are doing in your function is:
Convert a JavaScript object into an array of key/value pairs.
Iterating through the pairs and:
a. If the value is null do nothing.
b. If the value is an object, apply this logic to it using recursion.
c. If the key is name push the value to an array called result accessed through a Clojure.
Your function is grabbing any value whose key is name. That is why both foobar and Foo are returned.
Looking at Apache Avro's documentation I see that inside the fields key, there is a list with multiple field objects, each of which must have a name key.
So, assuming that you would like to get the values of all the field names you could do something like this:
// JSON object gotten directly from Apache Avro's documentation.
var avroRecord = {
"type": "record",
"name": "LongList",
"aliases": ["LinkedLongs"], // old name for this
"fields" : [
{"name": "value", "type": "long"}, // each element has a long
{"name": "next", "type": ["null", "LongList"]} // optional next element
]
}
function getFieldsNames(record) {
return avroRecord.fields.map((field) => {
return field.name;
});
}
console.log(getFieldsNames(avroRecord))
// [ 'value', 'next' ]
I hope this helps.

How can I remove null from JSON object with AngularJS?

I'm trying to remove an object from Json Object it works..but it replace it with null..i dont know why, how can i remove the null value from the json..heres the function :
company.deleteExternalLinkFromGrid = function (row, matricule) {
// console.log('Inside of deleteModal, code = ' + code);
//$scope.sitting= {};
console.log(matricule);
//console.log(JSON.stringify(linkJsonObj));
delete linkJsonObj[matricule];
console.log(JSON.stringify(linkJsonObj));
};
heres the object:
[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null]
You can use filter(), x will be without null's.
function test()
{
var x =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null].filter(isNotNull);
alert(JSON.stringify(x));
}
function isNotNull(value) {
return value != null;
}
fiddle
There are multiple ways to delete an object from an array of objects in JavaScript. You don't need AngularJS for that, you can use VanillaJS.
If you just want the nulls filtered you can use
var yourArray =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null];
yourArray = yourArray.filter(function(elt){
return elt != null;
});
But this loses the original reference to your object.
If you want to keep the reference, Use array.splice().
yourArray.forEach(function(){
yourArray.splice(yourArray.indexOf(null),1);
});
now you will have null less array in yourArray. This actually deletes an object from an array without changing the reference,
delete will replaced the object with undefined
You can filter the array to remove them using Array#filter()
var array = [{
"name": "xxx",
"link": "www.ddd.com",
"id": 0,
"$$hashKey": "uiGid-001Z"
}, {
"name": "xx",
"link": "www.dddcom",
"id": 1,
"$$hashey": "uiGrid-0029"
}, {
"name": "xxx",
"link": "www.ddd.com",
"id": 2
}];
delete array[1];
array = array.filter(a=>a);
console.log(JSON.stringify(array));

How to insert json values into object

I have a predefined object (SampleObject) like this:
{
ID: "",
Name: "",
URL: "",
prevName: "",
Code: "",
}
And I want to insert the below json object values(values only):
var object =
{
"Sample" : {
"Data" : {
"ID" : "12345",
"Name" : "SampleName: Name",
"URL" : "www.google.com",
"prevName" : "phones",
"Code" : "USD"
}
}
into the above predefined object. How do I do that?
You can just use a for in loop and set the value checking if the key is present in the object or not.
Check if the property is present on the emptyObject, and then copy that over to it.
for (var key in pageInfo) {
var value = pageInfo[key];
if (obj.hasOwnProperty(key)) {
obj[key] = value;
}
}
Code Pen
It is an object. There is no reason to use push or another method.
Simply take your defined object pageObject.page and assign a new key value pair with literal syntax.
pageObject.page['pageInfo'] = predefinedObject
or in more common syntax
pageObject.page.pageInfo = predefinedObject
Use the following code below the JSON Object
var digitalData= {page:{pageInfo:''}};
digitalData.page.pageInfo = pageObject.page.pageInfo;
console.log(digitalData.page.pageInfo);

Categories