Writing a static array of objects - javascript

I need help formatting this response. Below is a response that I'm getting from a server. I'd like to write out a static version of this but I'm struggling with the formatting of how to write it.
Response I want to write:
[
category1: [{...},{...}],
category2: [{...},{...}],
category3: [{...},{...}]
]
My attempt:
const myArr = [
"category1": [{...},{...}],
"category2": [{...},{...}],
"category3": [{...},{...}]
]
What is it that I'm doing wrong here? Thank you! Apologises for the n00b question.

You've written something that's a cross between an array literal and an object literal. It needs to be one or the other.
An array literal, containing arrays of objects:
const myArr = [
[{/*...*/},{/*...*/}],
[{/*...*/},{/*...*/}],
[{/*...*/},{/*...*/}]
];
You access the "category1" array via myArr[0], "category2" via myArr[1], etc.
An object literal, containing arrays of objects as the values of properties:
const myObj = {
category1: [{/*...*/},{/*...*/}],
category2: [{/*...*/},{/*...*/}],
category3: [{/*...*/},{/*...*/}]
};
You access the "category1" array via myObj.category1, "category2" via myObj.category2, etc.
Although it's possible to give arrays arbitrary named properties (because arrays are objects), you can't do so in an array literal (you have to create the array first, then add the properties), and you usually don't want to do it anyway. :-)

You can only use keys in an object not in an array. Try like this:
const myArr = {
"category1": [{...},{...}],
"category2": [{...},{...}],
"category3": [{...},{...}]
};

Something is wrong from that request because there is no result format like that. Make sure you have the correct response.
Object version:
const myArr = {
"category1": [{...},{...}],
"category2": [{...},{...}],
"category3": [{...},{...}]
};
console.log(Object.keys(myArr).map((key) => myArr[key]));

Related

map a 3 nested array javascript

const aboutMe = [{
"name": "frank",
"about": [{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": []
}
]
}]
const AllBreak = aboutMe.about.map((dinner) => ((dinner.first, dinner.last)));
const expectedOutput =["first": "desert", "last": "noodles", "first": "desert", "last": "noodles"]
console.log(aboutMe, AllBreak, expectedOutput)
so am trying to filter through a nested array learning from a tutorial I don't know why it returns cannot read property of map why is that pretty sure i filtered correctly according to the tutorial
Firstly, aboutMe is an array with an object that has an about property in it. So, if you want to access this property, you need to first access the first element of the array and then access the about property in it.
Secondly, (dinner.first, dinner.second) doesn't actually make any sense here.
Because when you have multiple expressions separated by commas in a bracket, each of those expressions get evaluated but only the last one is returned. So, here returning (dinner.first, dinner.second) is equivalent to returning dinner.second.
So, if you only want dinner.second then just return that or put them in an array (or object) and return that.
Also, since in your example it seems that it is not guaranteed that the dinner array would always have an object inside it, it is best to use Optional Chaining here.
Please have look at the solution below:
const
aboutMe = [{name:"frank",about:[{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[]}]}],
res = aboutMe[0].about.map(({dinner}) => [dinner?.[0]?.first, dinner?.[0]?.last])
console.log(res);
aboutMe is an array, if you want to get the property of the first element, you can use indexing [0]
const AllBreak = aboutMe[0].about.map(() => ...);

Intersecting two objects in angular 2

What I want to do is intersect two objects.
I want to compare the objects, and if they have same values on same keys, just add them to another object.
obj1 = { "Projects": [ "test" ], "Companies": [ "facebook", "google", "yahoo" ], "Locations": [ "LA", "NY" ], "Interests": [] }
obj2 = { "Projects": [ "test" ], "Companies": [ "netflix", "skype", "facebook" ], "Locations": [ "sttugart", "torino", "LA" ], "Interests": [] }
The result will be:
obj3 = { "Projects": [ "test" ], "Companies": [ "facebook" ], "Locations": [ "LA" ], "Interests": [] }
What i tried is something like this:
intersect(obj1, obj2)
for(let key of obj1)
if(obj2[key] == obj1[key]) obj3[key] = obj2[key];
And yes, i did checked SO for other solutions, i had no result.
EDIT
My attempt dind't probably work because my object is not an array type or a string type
This isnt really a problem just for angular 2 but more javascript in itself. No angular functions will probably help you here
Using lodash or underscore.js might prove to be more productive and useful
However if you insist that you need to do this in your own way. there are two cases
One is that you already know how many objects you would be comparing
Two is that you don't know how many objects you would be comparing
For case one it would a simple for loop with && cases for logical comparisons
For case two i would suggest you first push all your objects that need to be compared into an array and iterate through there.
Use lodash
Here you will find a good documentation:
https://lodash.com/docs/4.16.2#intersection
We often use it with good experience

trying to get value in JSON string from amount

I've got a JSON string and I can't seem to extract the value from the amount attribute
var jsonString =[{"id":null,"recordtype":null,"columns":{"amount":1049.849}}]
I've tried accessing amount using:
jsonString[0].columns[0].amount
and also tried using:
jsonString.columns.amount
but all seem to generate an error.
It is
jsonString[0].columns.amount
Because the value under "columns" is immediately an object, not an array.
jsonString[0].columns.amount
is the way to go. Columns is not an array
Try this,
jsonString[0].columns.amount;
You have an array, then just objects. So the answer is jsonString[0].columns.amount
It's useful to indent it, if in doubt:
[{
"id": null,
"recordtype": null,
"columns": {
"amount": 1049.849
}
}]
You have to create the JSON object like
var jsonString =[
{
"id":null,
"recordtype":null,
columns:
{
"amount":1049.849
}
}
]
Then you can access with jsonString[0]['columns']['amount'];
Here is the jfiddle link,
https://jsfiddle.net/hhLahiru/n0de3Lc8/
i can do on console
var jsonString =[{"id":null,"recordtype":null,"columns":{"amount":1049.849}}];
jsonString[0]
Object {id: null, recordtype: null, columns: Object}
jsonString[0].columns
Object {amount: 1049.849}
jsonString[0].columns.amount
1049.849

Are references possible in JSON?

Is it possible to assign references to objects in JSON? I have data that looks like this:
[{
name:"name",
Parent:[{
name:"parentName"
Parent:[{
.....//and so on
}]
}]
}]
I need to traverse it in JavaScript and also change the person's name. How can I do this?
Old question but some possibly new answers like JSON Spec and JSON Reference https://json-spec.readthedocs.io/reference.html
[{
"name": "John",
},
{
"name" : "Jack",
"parent": {"$ref": "#/0"}
},
...
]
or possibly better with JSON Path syntax http://goessner.net/articles/JsonPath/
[{
"name": "John",
},
{
"name" : "Jack",
"parent": {"$ref": "$.[?(#.name=='John')]"}
},
...
]
You can't. You can specify the path to the parent as a string and evaluate that at runtime, but as JSON is just strings, integers, arrays, and dictionaries, you can't use references.

Nested JSON objects - do I have to use arrays for everything?

Is there any way to have nested objects in JSON so I don't have to make arrays out of everything? For my object to be parsed without error I seem to need a structure like this:
{"data":[{"stuff":[
{"onetype":[
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
]},
{"othertype":[
{"id":2,"company":"ACME"}
]}]
},{"otherstuff":[
{"thing":
[[1,42],[2,2]]
}]
}]}
If I fetch this object into a variable called "result" I have to access the nested objects like this:
result.data[0].stuff[0].onetype[0]
and
result.data[1].otherstuff[0].thing[0]
This seems clumsy and redundant to me, if possible I would prefer:
result.stuff.onetype[0]
and
result.otherstuff.thing
But how can I use the object keys directly when everything is an array? To my confused and uneducated mind something like this would seem more appropriate:
{"data":
{"stuff":
{"onetype":[
{"id":1,"name": ""},
{"id":2,"name": ""}
]}
{"othertype":[
{"id":2,"xyz": [-2,0,2],"n":"Crab Nebula","t":0,"c":0,"d":5}
]}
}
{"otherstuff":
{"thing":
[[1,42],[2,2]]
}
}
}
I've probably misunderstood something fundamental here, but I cannot get the jQuery parser (nor the native FF parser used by jQuery 1.4) to accept the second style object. If anyone can enlighten me it would be gratefully appreciated!
You don't need to use arrays.
JSON values can be arrays, objects, or primitives (numbers or strings).
You can write JSON like this:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
You can use it like this:
obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.
Every object has to be named inside the parent object:
{ "data": {
"stuff": {
"onetype": [
{ "id": 1, "name": "" },
{ "id": 2, "name": "" }
],
"othertype": [
{ "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
]
},
"otherstuff": {
"thing":
[[1, 42], [2, 2]]
}
}
}
So you cant declare an object like this:
var obj = {property1, property2};
It has to be
var obj = {property1: 'value', property2: 'value'};
You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.
use each() wrap within another each() until the last array.
for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:
$.each(data.result.data, function(index0, v) {
$.each(v, function (index1, w) {
$.each(w, function (index2, x) {
alert(x.id);
});
});
});

Categories

Resources