I am new to Javascript and trying to convert data that I am getting from mongodb into multi dimension array like example below. If this could have been simple conversion of values in straight array than this could have been done using for loop but not sure how multi dimension array conversion can be done?
Please help.
[
{
"text": "p",
"count": 26
},
{
"text": "ne",
"count": 5
},
{
"text": "n",
"count": 69
}
]
Need multi dimension array like below:
[["p",26],["ne",5],["n",69]]
You can put the array through Array.protoype.map, which replaces each value in the array with whatever the callback function returns. In the callback function you can return an array version of the object.
For example:
var result = yourArray.map(function (item) {
return [item.text, item.count];
});
More array methods can be found on the MDN docs for Arrays.
Related
I am trying to use the .includes( ) array method to check if an item is in my JSON file. So far I have made a connection to the database (using JSON server npm plugin) and have retrieved the array of objects back, and stored them in the variable "fetchedData". Now, I know that .includes( ) takes an array as the first argument and searches within the array for the second argument. How do I convert this array of objects to an array including just the name property values? Is this how .includes( ) works?
This is the JSON file:
"savedexercises": [
{
"name": "all fours squad stretch",
"target": "quads",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1512.gif",
"id": 1
},
{
"name": "ankle circles",
"target": "calves",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1368.gif",
"id": 2
},
{
"name": "arm slingers hanging bent knee legs",
"target": "abs",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/2355.gif",
"id": 3
}
]
}
I am just trying to access all the name property values and then store them into an array.
Use array.map(). For example:
const exerciseNames = savedexercises.map(exercise => exercise.name)
// Expected output:
// ["all fours squad stretch", "ankle circles",
// "arm slingers hanging bent knee legs"]
// Now you can check if the exerciseNames includes a certain exercise:
console.log(exerciseNames.includes("all fours squad stretch"))
// Expected output: true
You can you filter and map to find all the values of a particular key and transform it to an array of objects or any form. Includes will only tell you if such a key exists. Refer the code below
const createArraybasedOnkey= (key) => {
console.log(
obj.savedexercises
.filter((x) => x[key])
?.map((x) => {
return { [key]: x[key] };
})
);
};
code sandbox : https://codesandbox.io/s/pedantic-rain-u1t9th?file=/src/App.js:625-817
I would like to be able to type in "Hammerhead" to call the "Hammerhead Shark" object without its full name. Is this possible and if so how?
I tried using array.indexOf(string) though it doesn't really seem to help since it requires an exact match such as typing "Hammerhead Shark"
JS:
const JSON = require('animals.json');
var animals = Object.keys(JSON);
if (animals.indexOf("Hammerhead")) {
console.log(JSON["Hammerhead"].name);
}
JSON:
{
"Hammerhead Shark": {
"name": "Shark",
"age": "300"
},
"Duck": {
"name": "Duck",
"age": "1000"
}
}
I expect the output to be "Shark" instead of undefined.
It seems you want to get access the value in object. By its partial name.
Get the entries of object using Object.entries()
Find the key which includes() the given partial key.
return the second element of the found entry.
const obj = { "Hammerhead Shark": { "name": "Shark", "age": "300" }, "Duck": { "name": "Duck", "age": "1000" } }
function getValueByPartialKey(obj,key){
return (Object.entries(obj).find(([k,v]) => k.includes(key)) || [])[1]
}
console.log(getValueByPartialKey(obj,"Hammerhead"))
You can use string.includes(word) to return the name that matches the string that you're searching for, along with Array.filter iterates over the values too, and returns the result(s) you want.
I have following object, and if I want to retrieve only soccer, then I put soccer as follows,
sports['soccer'] does not bring it.
I wonder what I am missing here?
sports = [] ;
sports = [{
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}]
Your current code creates an array with a single object. One solution is to just create an object instead:
sports = {
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}
Now you can use sports.soccer or sports['soccer'] to access the soccer data.
If you really want an array of objects, you first need to subscript the array to get the first object:
sports[0].soccer
or
sports[0]['soccer']
var sports is an array with objects inside.
If you set it up like this:
sports = [] ;
sports = {
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}
then you will be able to call sports['soccer'] or even sports.soccer.
Alternately, if you need it to remain an array, then you'll need to do more work.
Something like this should do the trick.
for(i=0; i < sports.length; i++) {
if("soccer" in sports[i]){
console.log(sports[i].soccer.type);
console.log(sports[i].soccer.player);
}
}
The console.logs represent whatever you want to do with the values
I think you really need to reiterate the basics of javascript a bit.
In JS we can create data structures on the fly with literal syntax. For example:
let normalArr = new Array();
let literalArr = [];
let normalObj = new Object();
let literalObj = {};
When you create arrays and objects with literal syntax you can initialize arrays with elements and object with properties on the fly. This is what exactly happened in your example:
sports = [{
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}];
The code can be broken down in the following way:
You created an array which was stored in the sports variable using the array literal syntax (created an array on the fly).
You created 1 element of the array with the object literal syntax (creating an object on the fly)
This object (located inside the array) has 2 properties, soccer and basketball which are also object created with object literal syntax.
To access one of there objects you need to do the following:
const sports = [{
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}];
// accessing the first element of the sports array
console.log(sports[0].soccer);
console.log(sports[0].basketball);
As others have pointed out, you have an array of objects, not a single object. You can use the find() method to find the element that has the soccer property, and then access that property.
var soccer = sports.find(s => 'soccer' in s)['soccer'];
I have a object with that values :
category_list = {
"1000":{
"name":"Cars",
"order":"1",
"level": "2"
},
"2010":{
"name":"Houses",
"order":"2",
"level": "2"
},
"1030":{
"name":"Cars",
"order":"3",
"level": "2"
}
}
And when I would like to show it Chrome reorders it based on the Index :
It becomes :
category_list = {
"1000":{
"name":"Cars",
"order":"1",
"level": "2"
},
"1030":{
"name":"Cars",
"order":"3",
"level": "2"
},
"2010":{
"name":"Houses",
"order":"2",
"level": "2"
}
}
I wish to keep the order as it was when pushing! or reorder based on field "order"
Can someone please help with that?
JavaScript objects are by definition unordered.
If you need an ordered list, you should use an array (of objects) instead, e.g.:
var objs = [
{
"key": 1000,
"name":"Cars",
"order": 1,
"level": 2
}, ...
];
objs.sort(function(a, b) {
return a.order - b.order;
});
NB: for numeric properties use numeric types.
JavaScript objects do not guarantee a specific order for their attributes. So the structure you'd like to have simply doesn't exist in JavaScript.
So with the native structures you can get either:
Array: Guaranteed order, but only accessing elements sequentially or by a numeric (0..n-1) index
Object: Arbitrary order, but you can access elements sequentially (again, arbitrary order) or using its key (which can be any string)
If you need both you either need to add an array that maps the order to the object keys, e.g. [1000, 2010, 1030] or store the data in an array and create a mapping like this: {1000: 0, 2010: 1, 1030: 2}.
The data which I fetch from PHP page is like:
[{
"id": "1",
"name": null,
"startdate": "2012-07-20",
"starttime": "09:53:02",
"enddate": "2012-07-20",
"endtime": "09:54:10",
"duration": "01:00:00",
"feedbacks": [{
"id": "1",
"type": "1",
"content": "cont"
}],
"conditions": [{
"id": "1",
"dev_id": "1",
"mod_id": "2",
"sub_id": "3",
"to_be_compared_value": "1",
"comparison_type": "1"
}],
"actions": [{
"id": "1",
"dev_id": "1",
"mod_id": "1",
"sub_id": "1",
"target_action": "1"
}]
}]
Which way is easy, efficent and elegant to traverse this object? I used this two until this time. Can you tell me which one must be my choice, or can you give me an alternative? And why? I have a running version of my application and I'm reviewing now my own code, and I want to take some advices from you all.
Thanks in advance,
Methods I use before:
$.map
for(var i in obj)
One more to go, I will create a table from this data.
I would use jQuery's each() (or map() if I wanted to change the data)
I should add that you should also create a function which returns an object (possibly even with some utility methods), since your data isn't very JS-friendly right now. Those dates and times, those ID's as strings.
Example:
function cleanMyObject(object){
var cleanFeedbacks = function(feedbacks){
/* ... */
return feedback;
};
object.start = /* transform date and time strings to datetime object ...*/
object.end = /*...*/
/*...*/
$.map(object.feedbacks,cleanFeedbacks);
/* cleanup the remaining objects... */
return object;
}
$.map(receivedData, cleanMyObject);
// cleanMyObject() returns the modified object so $.map will clean everything in your array.
I prefer to use http://underscorejs.org/ for things like this. It has a lot of useful functions for objects, collections etc.
If the data you are recieving doesn't change, just parse the object and use the keys you need.
All browsers I'm aware of have a function called JSON.parse to convert a JSON string into a JS object.
What I'm trying to say is: Don't be lazy, you aren't gaining any benefits from writing a "general" function if your object will always provide the same data, and there is little to no chance you can use that function again with a different object.
var myobj= JSON.parse(phpJSONstring);
var feedbacks= myobj["feedbacks"];
//do something with feedbacks
var conditions= myobj["conditions"];
//do something with conditions
etc
You can transform the json string in a javascript object, and then access the object like this:
var obj = jQuery.parseJSON(jsonString);
alert('Id='+obj.id);
var feedbackList = obj.feedbacks;
for (var i=0; i<feedbackList.length; i++) {
...
}
Reference to jQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/