Accessing specific values in JSON object - javascript

I can't figure out what I'm doing wrong when accessing this JSON object:
{ Items:
[ { mId: 'who' },
{ mId: 'am' },
{ mId: 'I' } ],
Count: 3,
ScannedCount: 3 }
{ Items:
[ { cId: 'big' },
{ cId: 'scary' },
{ cId: 'muppet' } ],
Count: 3,
ScannedCount: 3 }
This is the object I am getting back from a function and I'm trying to access the individual items to update their values.
When I want to print 'who' for example, I do this:
console.log(obj.Items[0].mId)
Now I expect to get 'who' back, but this is what prints:
undefined
who
That 'undefined' always tags along. What am I doing wrong here?
Also, if I try to change the value somewhere by doing:
obj.Items[0].mId = 'x'
This happens:
{ Items:
[ { mId: 'x' },
{ mId: 'am' },
{ mId: 'I' } ],
Count: 3,
ScannedCount: 3 }
{ Items:
[ { cId: 'big', mId: 'x' },
{ cId: 'scary' },
{ cId: 'muppet' } ],
Count: 3,
ScannedCount: 3 }
This is not what I want.. I don't understand how to access only the first 'Items'. It seems like I'm accessing both.
Any help or advice is greatly appreciated. I probably don't need to say that I'm not very used to working with JSON.

For the undefined issue, please see the answer here: What does it mean if console.log(4) outputs undefined in Chrome Console? but TL;DR you're just seeing the 'undefined' return from console.log(), because it has no return value. It shouldn't be an issue once you're not working in the console.
As for how you have 2 separate objects both called obj, I don't understand, as other said in the comments, please post the full code so we can see how this is being used/generated.
Also for clarification it looks like you're working with JavaScript objects, not JSON, similar but not the same.

Related

How to add a new object to another within an array [duplicate]

This question already has answers here:
How to append something to an array?
(30 answers)
Closed 2 years ago.
I have an array which looks like this:
array = [
{code1:
{
number: 2,
name: "e"
}
},
{code2:
{
number:2,
name: "u"
}
}
]
and I want to add the following as a new object to say "code1" without changing the data it now has.
{
number: 3,
name: "j"
}
how can I do it? Thank you!
1st approach
If I understood what you want to do correctly this could work:
array = [
{code1:
{
number: 2,
name: "e"
}
},
{code2:
{
number:2,
name: "u"
}
},
{code1:
{
number: 3,
name: "j"
}
}
];
2nd approach
However this would make the structure more difficult to traverse. As an alternative you could make the whole thing into a dictionary of arrays, like this:˛
let object = {//doesn't matter what we call it
code1:[
{
number:2,
name: "e"
},
{
number:3,
name: "j"
}
],
code2:[
{
number:2,
name: "u"
}
]
};
You'd go about accessing the new object like this: console.log(object.code1[0].number);
You can try this approach out in the snippet bellow.
let object = {//doesn't matter what we call it
code1:[
{
number:2,
name: "e"
},
{
number:3,
name: "j"
}
],
code2:[
{
number:2,
name: "u"
}
]
};
console.log(object.code1[0].number);
Closing statement
But as I've already said, I'm not sure if I understood your question correctly, I'd suggest editting the question to make it clearer in the future.
Thanks for reading
Internet person out.

Why is my object formulating differently in the console than it is when I run it through Tidy JS?

My Array of Objects is not appearing the way I want it to when I print it to the console. When I put it through Tidy JS, it formats it correctly. When I print it to the console, it looks incorrect.
What I want it to look like is:
Array
Object
Key:Value
Key:Value
Array
Object
Object
Object
Object
But instead its prints out how it does in this codepen:
https://codepen.io/anon/pen/qLrgKg
Any ideas as to why formatting it like it is in this codepen instead of how I want it to be?
var ArrayOfBlocks1 = [
{
ID:"1",
block: "block1",
BlockElements: [
{ blockElement1: { QuestionID: "1" } },
{ blockElement2: { QuestionID: "2" } },
]
},
{
ID:"2",
block: "block2",
BlockElements: [
{ blockElement1: { QuestionID: "1" } },
{ blockElement2: { QuestionID: "2" } }
]
},
{
ID:"3",
block: "block3",
BlockElements: [
{ blockElement1: { QuestionID: "1" } },
{ blockElement2: { QuestionID: "2" } }
]
}
];
You are printing the first element in the array rather then the whole array.
Change line 42 from console.log(ArrayOfBlocks1[0]) to console.log(ArrayOfBlocks1)

javascript [Object] inside my object instead of real data

I have the following js code https://repl.it/N0xy/0
I am trying to push some objects into an existing one using some functions:
mylist.push(createMyObject(item.name, item.school, item.teacher))
the result contains :
{ result: true, count: 1, items: [ [ [Object], [Object] ] ] }
instead of :
{ result: true, count: 1, items: [ { name: 'Jacky', school: 'high', teacher: 'good' },
{ name: 'Tom', school: 'college', teacher: 'bad' } ] }
how can i fix this?
thanks
You forgot to do JSON.stringify(obj) in the last statement. Everything else seems fine.
You might want to change the second last line to:
obj.items = create(); as well.
or maybe obj.items = obj.items.concat(create());
You pushed an array to obj.items in stead of the separate items. create() returns an array.
Try this:
create().forEach(function(item) {
obj.items.push(item);
});
OR
let createdItems = create();
for(item of createdItems) {
obj.items.push(item);
}
In your console.log at the end, wrap the obj in a call to JSON.stringify like this:
console.log("print my obj: ",obj);

Looking for a way to sort an array of objects in javascript

so I have a JSON array that looks like this:
[
{
row: [
{
boat: {
description: 'Books',
version: '2',
id: 6
},
airplanes: [
{
airplane: [
{
description: 'DVD',
version: 2,
uid: 69,
wid: 65,
id: 84
}
],
trains: {
train: [
{
description: 'Pictures',
version: 2,
id: 149
}
],
actions: [
{
description: 'This is a really long sentence.',
version: 2,
tid: 69.01,
id: 452
},
{
description: 'article 2',
version: 2,
tid: 69.02,
id: 453
},
{
description: 'developer 1',
version: 2,
tid: 69.03,
id: 454
}
]
}
},
{
airplane: [
{
description: 'Games',
version: 2,
uid: 65,
wid: 61,
id: 80
}
],
trains: {
train: [
{
description: 'another great descriptions.',
version: 2,
id: 145
}
],
actions: [
{
description: 'being indecisive is good.',
version: 2,
tid: 65.01,
id: 442
},
{
description: 'couches are comfortable',
version: 2,
tid: 65.02,
id: 443
}
]
}
}
]
}
]
}
]
I am trying to sort the above output by 'wid' in ascending order but still be able to preserve the overall order. For example in the above the wid in element 0 of the array is 65, and element 1 of the array the wid value is 61. Therefore, element 1 and element 0 should be swapped. Is there any built in javascript method to sort json like this?
I will have a json array output a lot larger than the provided example.
Both Underscore and LoDash have a sort method that will do what you're looking for. In this example I am assuming that you have the data structure you showed stored in a variable called data.
_.each(data, function(obj) {
_.each(obj.row, function(row) {
// note the reassignment, _.sortBy does not sort in-place
row.airplanes = _.sortBy(row.airplanes, function(airplane) {
return airplane.wid; // This will sort ascending.
// To sort descending, simply multiply by -1
});
});
});
So what is this doing? It's taking each array element in your root data structure and looping over it (that's the first _.each). Then in each of those objects, it is looping over each row element and sorting row.airplanes array by the wid element contained in each.
Hopefully this helps you. As an aside, that data you posted is strictly invalid JSON. Each key should be double quoted, i.e., "row", instead of just row and single quotes are invalid for delimiting strings, i.e., "DVD" instead of 'DVD'. Also, your boat version is a string whereas your other version identifiers are integers, it's a good idea to try and keep your version identifiers as integers.
I recommend using the excellent jq commandline JSON processor. Extremely fast since it was written in portable C. Easy to understand documentation.
cat <file.json> | jq . -S

What is the format of Express' req.params?

I've got a weird thing I'm running into with req.params while working with Express. It works fine for calling the subordinate properties - e.g.: res.json(req.params.paramName); gives me the desired paramName value. But when I tried to pass the entire res.params object to the client via res.json(req.params), I just get an empty array [] in the browser instead of the JSON object I was expecting. (res.send gives the same result.)
Looking a bit deeper, I dumped req.params to the console:
console.dir(req.params);
and got this:
[ creator: '1', timeStart: '2', timeEnd: '3', dateDensity: '4' ]
wut? Is that even syntactically possible in Javascript?
If req.params is a simple object like the Express code and documentation indicate, I should be getting:
{ creator: '1', timeStart: '2', timeEnd: '3', dateDensity: '4' }
An array like what I'm getting above should even be possible, should it?
I did some sanity checks and passed a couple of test objects to the console as well:
console.dir([{foo:1}, {arr:2}, {gog:3}, {blah:4}]);
console.dir({foo:1, arr:2, gog:3, blah:4});
and the console dump gives me:
[ { foo: 1 }, { arr: 2 }, { gog: 3 }, { blah: 4 } ]
{ foo: 1, arr: 2, gog: 3, blah: 4 }
So console.dir is working OK.
Lastly, I hardcoded a:
res.json({foo:1, arr:2, gog:3, blah:4});
into my Express code and the browser dutifully gives me:
{
"foo": 1,
"arr": 2,
"gog": 3,
"blah": 4
}
Am I smoking crack here? What is going on with req.params?
That's how v8 prints out arrays with string keys:
var myArr = [];
myArr.key = "oops";
Remember, [] instanceof Object is true.
req.params is an array, suggesting the possibility of positional params.

Categories