How I can build this json object with javascript code? - javascript

{
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
I don't understand how I can create object like "ma.addEvent"
the "dot" is a problem here.

Try this
var x = {
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
If you want to access, you have to use [] notation (. notation won't work, because of dots in keys) like
console.log(x["ma.addEvents"]["ma.id"])

You might want to use a square bracket notation:
var yourObject = {};
yourObject['ma.addEvents'] = {};
...and so on. Print the ma.addEvents attribute using
console.log(yourObject['ma.addEvents'])

You can use this:
var json_string = "{\"ma\.addEvents\":{\"ma\.id\":\"my-id\",\"ma\.eventIds\":[\"eventID1\",\"eventID2\"]}}";
The code above, when parsed to json (JSON.parse), will retrieve the same object that appears on your question.
Hope this helps,
Regards,
Marcelo

var obj = {
"ma.addEvents": {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
Depends on what part you would like to add dynamically.
var obj = {};
obj["ma.addEvents"] = {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
};
obj["ma.addEvents"]["ma.eventIds"].push("someotherEvent");
Please take a look at the documentation for accessors.

ma must be defined before you create ma.addEvents etc. The syntax might look like this:
// `ma` is an object
var ma = {
// It contains an object called `addEvents`
addEvents: {
// Which contains a string `id` and an array `eventIds`
id: "my-id",
eventIds: [
"eventId1",
"eventId2"
]
}
}
To create a blank object in ma, you could use the 'dot' syntax:
ma.newObject = {};
or square bracket notation:
ma["newObject"] = {};
I'm not entirely sure what your question is, are you looking to parse that JSON or to learn Javascript object syntax?

Related

Replace nested JavaScript Object data item with dynamically created path?

I've got this JSON data object (example):
let obj = [
{
test0: [
{testA: 'ContentA' },
{testB: 'ContenB'}
]
}
];
I'd like to replace the value of key 'testB' dynamically. I.e. I need to be able to address any item in the object and replace ist.
Here's what I am doing so far:
Therefore I programmatically generate a mixed key/index path to address the target object and it looks like this (in array form):
let path = [0,'\'test0\'',1,'\'testB\''];
In order to put this in an executable form which does the actual replacement, I convert path to JavaScript code and run it with eval. Like this:
let newText = 'ContentB';
eval(`obj[${path.join('][')}]=\'${newText}\'`);
Eval executes this code literal:
obj[0]['test0'][1]['testB'] = 'ContentB'
This works, but if possible, I'd like to know if there's an alternative way which works without using "eval".
You could use a recursive function and pass it the property path as an array of properties, like this:
function setDeepValue(obj, [prop, ...path], value) {
if (!path.length) {
obj[prop] = value;
} else {
if (!(prop in obj)) obj[prop] = {};
setDeepValue(obj[prop], path, value);
}
}
// Example:
const arr = [{
test0: [
{ testA: 'ContentA' },
{ testB: 'ContenB' }
]
}];
setDeepValue(arr, [0, "test0", 1, "testB"], "ContentB");
console.log(arr);
If you are OK with using a library, you could use Lodash, which has _.set and the more flexible _.setWith to do this.

How to get a key to be used as a variable in a lodash map function?

I'm trying to restructure an object for convience.
This is the general structure:
var dictionary = { "word": {"content": "wordy"}, "palabra": {"content":"palabrota" }};
I want it to look like this:
[{"wordy":"word"},{"palabrota":"palabra"}]
And I'm trying this code out:
_.map(dictionary, function(v,k){ var new_key = v.content;return { new_key: k };} );
But instead of what I am expecting, this is the result:
[ { new_key: 'word' }, { new_key: 'palabra' } ]
How to get a key to be used as a variable in this function?
You can use the _.invertBy method (as of LoDash v4.1.0), which will give you the key and an array of the values, thus ensuring the values aren't overwritten.
var dictionary = {
"word": {"content": "wordy"},
"anotherWord": {"content": "wordy"},
"palabra": {"content":"palabrota" }
};
var result = _.invertBy(dictionary, function(item) {
return item.content;
});
// "{"wordy":["word","anotherWord"],"palabrota":["palabra"]}"
EDIT: earlier response below. This works, however the limitation is duplicate content values would overwrite the keys. The docs for _.transform below shows how to generate an array to handle duplicates, and a similar setup can be used for the regular JS approach.
You can use the _.transform method:
var transformedResult = _.transform(dictionary, function(result, value, key) {
return result[value.content] = key;
});
Or without LoDash at all, you can construct the object as intended.
var result = {};
Object.keys(dictionary).forEach(function(key) {
var value = dictionary[key].content;
result[value] = key;
});
I might recommend _.mapValues(dictionary, "content") for simplicity.
However, instead of [{"wordy":"word"},{"palabrota":"palabra"}], instead you'll get {"wordy": "word", "palabrota": "palabra"} as the result from _.mapValues. But given that you're using lodash, and lodash treats arrays and objects pretty much interchangeably, I think the non-array version would be more convenient.

How to join multi arrays from Object properties in Javascript?

I am using AngularJS and I have a problem as below:
I have created an Object whose properties are arrays. For example:
$scope.myObject = {
import: [ object1, object2,...,objectN ],
export: [ object1', object2',...,objectN' ],
...
}
Now I want to create a new array which concats all arrays from myObject properties so that I can display them in HTML view with ng-repeat.
This is my Plnk sample code: http://plnkr.co/edit/Ca8OX7kX8wV8JmRYJCzS?p=preview
Please help me. Thanks.
With underscore or lodash :
_.flatten(_.values($scope.myObject));
See fiddle
I've added also a plain JS (EcmaScript 5+) method :
$scope.myObjectJS = [];
Object.keys($scope.myObject).forEach(function(key) {
$scope.myObjectJS = $scope.myObjectJS.concat($scope.myObject[key]);
});
The fact that I use Object.keys(obj) instead of for (var key in obj) exempts us to check for hasOwnProperty.
If I understand your question right this should work.
var newArr = [];
for(var key in $scope.myObject){
newArr = newArr.concat($scope.myObject[key]);
}

Create nested Json in js

I want to create Json like this:
{
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
}
I don't know how to place none-named property in json obj and place and obj into "children".
OK, if you mean key itself is variable then you cannot create json-object in single shot,
you will have to create it using '[]' notation
var myObj = {};
myObj[myProp1] = [] //or some value or some json/map again
myObj[myProp2] = 'hi'
myProp1 and myProp2 are variables.if you can explain your problem in more detail then you will get more clear answer.
If you ask how to manipulate that JSON object, then maybe this would help.
Your original object:
var object = {
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
};
1) How to place none-named property in json obj.
Object is not array, so should assign key/value, though either or both of them were empty. You can insert using dot or like array assignment.
object.country = "Malaysia";
object[""] = "No Keys";
object["novalue"] = "";
2) How to place an obj into "children".
var aNewChild = {
"childName": "Handsome one"
};
object.children.push(aNewChild);

Changing my simple JS Array to have key/values instead

Im currently using jQuery to build an Array like this:
var arr = new Array();
$('#some-form .some-input').each(function() {
arr.push($(this).val());
});
which builds something like:
arr[0] = 'bar'
arr[1] = 'foo'
Now I want a data structure (a 'map'? a JSON array?) to do get something like this:
{ 'key1' : 'foo'
'key2' : 'bar' }
because I am now going to store multiple 'things' from $('#some-form .some-input').
In C, I think this could be a linked list because you don't know how big the data structure will be in advance so you wouldn't use an array. However, I AM using an array here which might not be the best idea? What's sort of structure do I need?
Many thanks.
With javascript you can dynamically add properties to an object, so you can do something like this:
var arr = {};
$('#some-form .some-input').each(function() {
var $this = $(this);
arr[$this.attr('id')] = $this.val();
});
And you can access them with arr.key1; // foo
Edit: as the comments below note, you can also access the values using the [] notation, like arr['key2'] // bar (thanks for reminding me :))

Categories