I have JSON array with one object consisting of nodes and links.
data = [Object]=[ { nodes: Array[..] ,links: Array[…] } ]
This is all fine, but for accessing the links for example I have to use data[0].links, which is a bit annoying. I would like the array to be an object, so that data.links gives access to the links. I have tried to set:
data = data[0];
But then the array of Objects, data.links, are displayed as "undefined".It seems like when a specific element is accessed the value is displayed, for example data.links[3].name. Why is that?
Edit:
More specifically:
if data = [ { nodes: Array[... ] ,links: Array[...] } ] =>
console.log(data[0].links); //shows the data[0].links[0].name = value in the console
if data = { nodes: Array[... ] ,links: Array[...] } =>
console.log(data.links); //shows data[0].links[0].name = undefined
but interestingly
console.log(data.links[0].name); //shows the correct value.
A couple of solutions:
If you control the JSON output, simply remove the enclosing brackets [] those are basically wrapping your object in an array.
data = { nodes: [...] ,links: [...] };
If you don't control the JSON just simply assign the zero index of the array to the variable you actually want to work with.
json = [ { nodes: [...] ,links: [...] } ];
data = json[0];
Unfortunately, 'links' is an array. To access a member of that array, you will need to access its index value.
Related
I have a json array. I want to retrieve all "tag" values where listid=n;
[
{"listid":"1","tag":"ONE"},
{"listid":"1","tag":"TWO"},
{"listid":"1","tag":"THREE"},
{"listid":"2","tag":"ONE"},
{"listid":"2","tag":"TWO"},
{"listid":"2","tag":"THREE"},
{"listid":"2","tag":"FOUR"},
{"listid":"3","tag":"ONE"},
{"listid":"3","tag":"FOUR"},
{"listid":"3","tag":"TWO"},
{"listid":"3","tag":"SIX"},
{"listid":"3","tag":"FIVE"},
{"listid":"3","tag":"THREE"}
]
I have found how to search an array for an individual value, but I can't seem to find anything on returning multiple values I require, as a json array.
You can first filter for the items you want, then map to get the specific property you are after.
let a = [
{"listid":"1","tag":"ONE"},
{"listid":"1","tag":"TWO"},
{"listid":"1","tag":"THREE"},
{"listid":"2","tag":"ONE"},
{"listid":"2","tag":"TWO"},
{"listid":"2","tag":"THREE"},
{"listid":"2","tag":"FOUR"},
{"listid":"3","tag":"ONE"},
{"listid":"3","tag":"FOUR"},
{"listid":"3","tag":"TWO"},
{"listid":"3","tag":"SIX"},
{"listid":"3","tag":"FIVE"},
{"listid":"3","tag":"THREE"}
]
let n = "2"
let found = a.filter(item => item.listid === n).map(item => item.tag)
console.log(found)
This is assuming you want to do this in javascript
I have two arrays created from a reduce method that searches two existing arrays for dates. It then turns those dates into unique object keys.
The first group is a list of names the second is a set of series of instructions.
The goal is to combine the two arrays that get formed by finding like object keys and adding the matching list object and insert it into the set of instructions with the object key list.
For one it makes an array that looks like :
const listObj = [
{11/20/2020: [{name:'Joe', date:11/20/2020}]},
{11/26/2020 : [{name:'John', date:11/26/2020}]}
]
And this:
const scheduleObj = [
{11/20/2020: {type:'Federal', date:11/20/2020}},
{11/26/2020 : {type:'State', date:11/26/2020}}
]
The final product that i need would look something like:
const scheduleObj = [
{11/26/2020 : {
type: 'State',
list: [{name:'John', date:11/26/2020}]
},
...
]
Where the list is an added key and the array is the array that is associated with the object key
I have used a messy what looks like lodash method to get this to work, but I figure there has to be some sort of mapping I can do.
Any Help Would Be Appreciated
This can be little messy and not failure proof depending on what you have in your listObj or scheduleObj. E.g. repeated date in scheduleObj can lead to a problem using this method, you may have to use another key if the dates are no unique in both lists.
scheduleObj.map((s) => {
// get the first key of the object as the date you're going to group with
const date = Object.keys(s)[0];
// filter the object that matches the date
const listObjFilter = listObj.filter((o) => Object.keys(o)[0] === date);
// get the list for the given date (or empty array if nothing found)
const listForDate = listObjFilter.length ? listObjFilter[0][date] : [];
// build the result object
return {
[date]: {
type: s[date]['type'],
list: listForDate
}
};
})
Note that I'm always considering you have only one key in the objects inside the lists in listObj or scheduleObj.
I have data for example like this:
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}]
And I want to convert them into like this:
data: ['Apple','Microsoft','Google']
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
One way is to use Array.map and replace the object ele.tag with just the value return ele.tag:
var data =
[{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}];
data = data.map(function(ele){ return ele.tag; });
console.log(data);
Or in ES6 you can simply this even more:
data = data.map(ele => ele.tag);
You could use a for-in loop and push the attribute of the object into an array.
var data = [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}];
var tags = [];
for (prop in data) {
tags.push(data[prop].tag);
}
console.log(tags);
For easier handling let's take the object in the OP's code and assign it to a variable, as follows:
var obj = {"data":[{"tag":'Apple'},{"tag":'Microsoft'},{"tag":'Google'}]};
var {data}= obj; // object destructing ...
var mapped = data.map(function( e ){ return e.tag});
// re-assigning value of object's data property
obj["data"] = mapped;
console.log(obj); // obj.data now pertains to array of strings
The problem described by the OP involves an object whose data property refers to an array of objects, each with a tag property. The OP inquires as to how to revise the data property so that it refers instead to an array of string values corresponding to each object's tag property.
This example makes use of destructuring to access the array of objects. Then, it uses the array's map() method to access every element's tag property and thereby obtain its string value. The beauty of map() is that it performs iteration behind the scenes sparing the user from having to hand-code a loop with the correct logic -- although in functional programming languages instead of using iteration, recursion is more apt to be utilized for this purpose. Finally, the value of the object's data property is reset to contain the specified array of strings.
I need to map an object of arrays. Once mapped I want to display the first row of content in a div. I have an object of arrays coming from the db and I'm only mapping 2 of the 4 arrays within the object.
What I want to be able to do is use the mapped arrays and then get all the data that corresponds with that mapped array and display it all in a div. The user can click an up or down arrow and then change what is displayed, but I'm having trouble getting it to show the next or prev data in the object. I have the clicking function properly set up (worked with test data) just think it's not working because I'm not mapping it correctly.
Original object coming from db:
object: {
PageNum: [array of items],
RowNum: [array of items],
CustomerName: [array of items],
FacilityName: [array of items]
}
mapping the arrays:
var delDS = [{
pageNum : delPageData["PageNum"],
rowNum : delPageData["RowNum"]
}];
var delMappedArray = delDS.map(function(obj) {
var rObj = {};
rObj[obj.pageNum] = obj.rowNum;
return rObj;
});
which returns something like this:
[object]
0: Object
2,2,4,4,6: Array(5)
0: "24"
1: "26"
2: "2"
3: "4"
4: "10"
length: 5
Try something like this:
//map the data
delPD = delPageData.PageNum.map((x,i) => ({
pageNum: x,
rowNum: delPageData["RowNum"][i],
cName: delPageData["CustomerName"][i],
fName: delPageData["FacilityName"][i],
}));
//sort the data
delPD.sort(function(a,b) {
if(a.pageNum == b.pageNum) {
return (a.rowNum - b.rowNum);
} else {
return (a.pageNum - b.pageNum);
}
});
//give the data an index number for ordering purposes later
for(var i=0; i<delPD.length; i++) {
delPD[i].index = i;
}
This is first mapping the array of objects and creating a new array. Then you are sorting the new array by page numbers and putting them in order. Then you're adding an index number to each object. This way you can use it later in your code if need be.
Hope this helps!
I have this object i copied from my console
Object { input_name: "hi", input_type: "world", input_number: "200" }
which i had earlier put together this way
var post = {
input_name: name,
input_type: type,
input_number: number
};
console.log(post);
I am passing the data as an array to another function which does the inserting to a mongodb. I need to get the first,second and third values in seperate variables in order to be inserted into the database.
I have tried this
for (var key in post) {
var one = post[key];
console.log(one);
break;
}
and have only just got the first value. How can i hold the three values each in its own variable?.
You don't need to have new variable per each value. Just access object properties by it's keys:
console.log(post.input_name);
console.log(post.input_type);
console.log(post.input_number);
remove the break from your loop.. your code should be:
for (var key in post) {
var one = post[key];
console.log(one);
}