I made this object literal and I don't understand what is the right brackets positioning for the array that comes after active. Why am I getting missing brackets error?
var players = {
player1 : {
active : true,
[
{
row : 1,
square : 1
},{
row : 2,
square : 1
},{
row : 3,
square : 1
}
]
}
};
The value of the active property can be either the boolean true or an array. It can't be both.
You need to change it to either:
active : [ ... ]
or
active : true,
somethingElse : [ ... ]
or some other valid data structure.
First off, that's not JSON, that's a JavaScript object initializer (sometimes called an "object literal").
The problem is the [ here:
active: true,
[
You need a key before that value. The basic form is key: value, where the key is the name of the property (can be an identifier, a number, or a string in JavaScript; in JSON it would have to be a string, and in double quotes not single quotes) and the value is, well, the value. :-)
active is set to 2 values, true and your array. To test your JSON, use http://jsonlint.com/.
Related
I have this collection:
[{ "_id" : 7,
"category" : "Festival",
"comments" : [
{
"_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
"usr" : "Mila",
"txt" : "This is a comment",
"date" : "4/12/11"
}
]
}]
All I want is to push insert a new field inside comments like this:
[{ "_id" : 7,
"category" : "Festival",
"comments" : [
{
"_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
"usr" : "Mila",
"txt" : "This is a comment",
"date" : "4/12/11",
"type": "abc" // find the parent doc with id=7 & insert this inside comments
}
]
}]
How can I insert inside the comments subdocument?
You need to use the $ positional operator
For example:
update({
_id: 7,
"comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
},{
$set: {"comments.$.type": abc}
}, false, true
);
I didn't test it but i hope that it will be helpful for you.
If you want to change the structure of document you need to use
db.collection.update( criteria,
objNew, upsert, multi )
Arguments:
criteria - query which selects the record to update;
objNew - updated object or $ operators (e.g., $inc) which manipulate the object
upsert - if this should be an "upsert"; that is, if the record does not exist, nsert it
multi - if all documents matching criteria should be updated
and insert new objNew with new structure. check this for more details
The $ positional operator is only going to work as expected if the 'comments' field is NOT an array. The OP's json is malformed, but it looks like it could be an array.
The issue is that mongodb right now will only update the first element of an array which matches the query. Though there is an RFE open to add support for updating all matching array elements: https://jira.mongodb.org/browse/SERVER-1243
To work around this issue with arrays you just have to do a regular find then update the elements in the array individually.
This is the javascript Object (just a small part of it):
dataToReturn = {
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}
So in PHP it will look like:
<?php
$jsObjStr = '{
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}';
But if we would like to parse it with json parse we cant In PHP since its not a clean JSON format because of
"dimensionsDisplayType" : [
"dropdown","swatch",
]
The keys containing object like "dimensionsDisplayType" can be unpredictable so cleaning with regex for example wont help much.
The one that works is
JSON.stringify(dataToReturn)
But in my case I can not run client side code sot it must be converted into the correct JSON format in server side with PHP. I was searching a lot online but I got not any satisfying function or library.
How can this be solved ?
You could try cleaning the string with this regex, this will look for a comma followed by optional whitespace and a close ] and replace this with the content minus the comma...
$jsObjStr = preg_replace("/,(\s*?])/", "$1", $jsObjStr);
I have an array of object in Javascript that I want to subset based on key-value matches. In principle I want to access my array js_obj, change some objects where cond is true and then move on.
Let's say the array looks like this
js_obj = [{
word: "airport",
pic: "<img id='pic' src='../images/location/airport.png'/>",
cat: "location",
type: "undetermined"
}, {
word: "station",
pic: "<img id='pic' src='../images/location/station.png'/>",
cat: "location",
type: "undetermined"
}]
I now want to access js_obj where .word == "station" and of this selected object I want to change .type to "type_abc".
I was able to use each and select the object where the condition applies and change its .type as wanted, but I would like to do this within the original array. I do not simply want to filter out this object but find it, edit it, and leave the array in the modified state.
I found related posts referring to underscore.js but I think I didn't know which method to look for.
Can anybody help me with this indexing/subsetting problem?
Looping the array, checking the condition and modifying will keep it in the original array:
function modifyArrOfObjs(arr, key, condition, updateKey, updateValue) {
arr.forEach(function(obj) {
if (obj[key] == condition) {
obj[updateKey] = updateValue;
}
});
}
modifyArrOfObjs(js_obj, "word", "station", "type", "type_abc");
I need to pull the value of property "title"
KV = {
clientPath: '/0000000000/client',
serverPath: '',
application: '/00000000/client/application/player.js',
properties: '/000000000/client/custom-config/AppProperties.js',
pollingEnabled: false,
customerConfig: {},
presentationTypeConfig: {},
kuluConfig: {},
kulu: {
"guid" : "XXXXXXX",
"title" : "XXXXX",
"createdInApp" : false,
"allowFeedback" : true,
"publisher" : {
"id" : 000000001,
"username" : "XXXXXXX",
"name" : "XXXXXXXX"
},
I tried looping but I just get returned undefined.
I have no access to the code to change it.
Have you tried this?
KV.kulu.title
first of all: the json you have posted is invalid. publisher-property has only an opening curly bracket.
second: here's a working fiddle, with valid json and just the code kv.kulu.title which does exactly what you are (literally) asking for:
http://jsfiddle.net/k75cxdkh/1/
edit: I'm just guessing here, but re-reading your question and json code, it seems you try to loop over an array of objects to get a nested object by it's value dynamically. When trying this, do it e.g. like this (using underscorejs):
var arr = _.filter(KV, function(obj) {
return _.some(obj.kulu, {id: ID_TO_FIND});
});
if not, nevermind. It's just a bit weird you are asking for a such common task.
quick and easy: KV.kulu.title no loop required!
I need to access the "State" value from the following array --
data =
{
Images:
[
{
ProductCodes: [],
BlockDeviceMappings: [Object],
Tags: [],
ImageId: 'ami-75301c',
ImageLocation: '54696560/Test Image 3',
State: 'available',
VirtualizationType: 'pavirtul',
Hypervisor: 'xen'
}
],
requestId: '2eb809d3-7f82-4142-b5d1-6af3'
}
When I try data.Images["State"] or data.Images.State I get undefined.
Thanks
Images maps to an array which stores objects, so you have to specify the index of the item you want. Try data.images[0]["State"].
You can access like this:
data.Images[0].State
Or even:
data.Images[0]['State']
Access the state with data.image[0].state. Your method was wrong because inside the image, you need an index within the two square bracket, the image property is an array.