Dynamically add object in javascript array - javascript

I have json:
var obj = '{"Form":[],"Provider":[]}';
I push the data with variable value to make dynamic objects:
var pName = 'Tester';
var data = {
pName :["testing"]
};
console.log(obj['Provider'].push(data));
But that adds pName as variable name but not variable value that is Tester, i tried with +pName+ that also not works.
Returns:
{"Form":[],"Provider":[{"pName":["Testing"]}]}
Any help would be appreciated.

You must use [] syntax near the property name.It will evaluate the expression in the [] and returns the value.
See the example.Here the data's property is with the name 'Tester'.
var obj = {"Form":[],"Provider":[]};
var pName = 'Tester';
var data = {
[pName] :["testing"]
};
console.log(data.pName); // undefined
console.log(data.Tester); // OK
obj['Provider'].push(data);
console.log(obj);

Related

Adding a key/value pair at the same time as creating a sub-object

I am new to working with objects. I want to:
Add a key
Add a sub-object to that key
Push the key/value pair to this sub-object.
For example, the data structure I am looking to achieve would be:
invalidFields = {
"_0" : {
"firstName" : "foo",
"lastName" : "la",
}
}
The addition of the most nested key/value pair is done by iterating and comparing, so in essence it needs to be added to "_0", not overwriting it.
So far I have:
let invalidFields = {}; // this is initialised outside of the for loop
...
const field = "foo";
const passengerIdentifier = "_" + passengerIndex; // "_0"
const fieldKey = "firstName";
invalidFields[passengerIdentifier] = field;
This adds the key/value pair of "firstName": "foo" but when the loop continues it therefore overwrites it so the data I get is only field applied :
invalidFields = {
"_0" : "foo",
}
This is obviously not correct as I need the key/value pairs to add to the "_0" sub-object. What am I doing wrong?
Edit: Here is an example of what I have now, but this does not seem to work, the field part isn't added:
const passengerIdentifier = '_'+passengerIndex;
if (!invalidFields[passengerIdentifier]) {
Object.assign(invalidFields, { [passengerIdentifier] : '' });
Object.assign(invalidFields[passengerIdentifier], { [fieldKey]: field });
}
To add key/value pair to each sub-object use the following approach:
...
var field = "foo",
passengerIdentifier = "_" + passengerIndex, // "_0"
fieldKey = "firstName";
// assuring sub-object with certain `passengerIdentifier`
invalidFields[passengerIdentifier] = invalidFields[passengerIdentifier] || {};
invalidFields[passengerIdentifier][fieldKey] = field;
You could use Object.assign and add the new key/value to the existing object in the loop.
// outside of the loop
invalidFields[passengerIdentifier] = {};
// inside of the loop
Object.assign(invalidFields[passengerIdentifier], { [fieldKey]: field });
Just for completeness, it is possible, to assign a value directly to an object
// inside of the loop
invalidFields[passengerIdentifier][fieldKey] = field;
let invalidFields = {}; // this is initialised outside of the for loop
...
const field = "foo";
const passengerIdentifier = "_" + passengerIndex; // "_0"
const fieldKey = "firstName";
var subObject = {
'key1' : value1,
'key2' : value2,
// add all keys
}
invalidFields[passengerIdentifier] = subObject ;
Does this do what you're trying to achieve?
invalidFields[passengerIdentifier] = {
[fieldKey]: field
}

str.split to json with names

I have taken a string that is "title:artist" and used str.split :
res = song.split(":");
Which gives me an output of :
["Ruby","Kaiser Chiefs"]
I was wondering how I could add name to this so that it appears as :
["name":"Ruby", "artist":"Kaiser Chiefs"]
var res = song.split(':');
var jsonString = JSON.stringify({ name: res[0], artist: res[1] });
You can find more information about how to use JSON.stringify here but basically what it does is takes a JavaScript object (see how I'm passing the data as an object in my answer) and serializes it into a JSON string.
Be aware that the output is not exactly as you have described in your question. What you have is both invalid JavaScript and invalid JSON. The output that I have provided will look more along the lines of {"name":"Ruby", "artist":"Kaiser Chiefs"}. Notice how there is {} instead of [].
["name":"Ruby", "artist":"Kaiser Chiefs"] isn't a valid format I guess you want to create an object so you could use just the split like :
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {'name': my_string_arr[0],"artist": my_string_arr[1]};
console.log(my_object);
Or also assign the values to the attributes separately like:
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {};
my_object.name = my_string_arr[0];
my_object.artist = my_string_arr[1];
console.log(my_object);
Hope this helps.
What you're looking for is: Object. Here is how you do it:
var str = "Ruby:Kaiser Chiefs";
var res = str.split(':');
// this is how to declare an object
var myObj = {};
// this is one way to assigne to an object
// using: myObj["key"] = value;
myObj["name"] = res[0];
// this is another way to assign to an object
// using: myObj.key = value;
myObj.artist = res[1];
console.log(myObj);

Is it necessary to create nested jSON objects before using it?

I think I've seen how to create a JSON object without first preparing it. This is how i prepare it:
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now I think I can insert a value like: obj.0.type = "type0"; But I'd like to create it while using it: obj['0']['type'] = "Type0";.
Is it possible, or do I need to prepare it? I'd like to create it "on the fly"!
EDIT
I'd like to create JS object "On the fly".
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now i think i can insert value like: obj.0.type = "type0";
I guess you mean "assign" a value, not "insert". Anyway, no, you can't, at least not this way, because obj.0 is invalid syntax.
But I'd like to create it while using it: obj['0']['type'] = "Type0";
That's fine. But you need to understand you are overwriting the existing value of obj[0][type], which is an empty object ({}), with the string Type0. To put it another way, there is no requirement to provide an initialized value for a property such as type in order to assign to it. So the following would have worked equally well:
obj = {
0:{},
1:{},
2:{}
};
Now let's consider your second case:
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
Think closely about what is happening. You are creating an empty obj. You can assign to any property on that object, without initializing that property. That is why the assignment to obj.test works. Then in your second assignment, you are attempting to set the test property of obj.test, which you just set to the string "test". Actually, this will work--because strings are objects that you can set properties on. But that's probably not what you want to do. You probably mean to say the previous, string value of obj.test is to be replaced by an object with its own property "test". To do that, you could either say
obj.test = { test: "test" };
Or
obj.test = {};
obj.test.test = "test";
You are creating a plain object in JavaScript and you need to define any internal attribute before using it.
So if you want to set to "Type0" an attribute type, inside an attribute 0 of an object obj, you cannot simply:
obj['0']['type'] = "Type0";
You get a "reference error". You need to initialize the object before using it:
var obj = {
0: {
type: ""
}
};
obj['0']['type'] = "Type0";
console.log(obj['0']['type']);
You could create your own function that takes key as string and value and creates and returns nested object. I used . as separator for object keys.
function create(key, value) {
var obj = {};
var ar = key.split('.');
ar.reduce(function(a, b, i) {
return (i != (ar.length - 1)) ? a[b] = {} : a[b] = value
}, obj)
return obj;
}
console.log(create('0.type', 'type0'))
console.log(create('lorem.ipsum.123', 'someValue'))
Is it necessary to create nested objects before using it?
Yes it is, at least the parent object must exist.
Example:
var object = {};
// need to assign object[0]['prop'] = 42;
create the first property with default
object[0] = object[0] || {};
then assign value
object[0]['prop'] = 42;
var object = {};
object[0] = object[0] || {};
object[0]['prop'] = 42;
console.log(object);
Create object with property names as array
function setValue(object, keys, value) {
var last = keys.pop();
keys.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var object = {};
setValue(object, [0, 'prop'], 42);
console.log(object);

accessing JSON value if key is array element

suppose i receive JSON object from the server as this
{ "asdf[zxcv]": "qwer" }
how do i access asdf, zxcv, and qwer in javascript, so i can use the object this way ?
theobj.asdf[zxcv] = 'qwer'
Bracket notation is not in the JSON RFC. You can only read it as string.
var simpleObj = {
"simpleKey": "simpleValue"
}
console.log(simpleObj)
var advObj = {
"advKey[1]": "advValue"
}
console.log(JSON.parse(advObj)); // SyntaxError
console.log(advObj.advKey[1]) // TypeError
console.log(advObj["advKey[1]"]) // can only read as string
You would need to refactor the source JSON into something more meaningful so you can access the values in regular JavaScript way.
Run the following snippet to check how you can solve the issue:
var x = '{ "asdf[zxcv]": "qwer" }';
var y = JSON.parse(x);
var result = Object.keys(y).reduce(function(result, key) {
var parentKey = key.substring(0, key.indexOf("["));
var innerKey = /[a-z]+\[([a-z]+)\]/i.exec(key)[1];
if (!result.hasOwnProperty(key))
result[parentKey] = {};
result[parentKey][innerKey] = y[key];
return result;
}, {});
document.getElementById("structure").textContent = JSON.stringify(result);
var zxcv = result["asdf"]["zxcv"];
document.getElementById("someValue").textContent = zxcv;
<h2>Refactored data structure as nested objects:</h2>
<div id="structure"></div>
<h2>Accessing some value: result["asdf"]["zxcv"] or result.asdf.zxcv</h2>
<div id="someValue"></div>
It's all about creating nested objects to represent the associative keys in the source JSON properties representing a conceptual associative array...
This is one of the way to access all elements without reconstructing object.
jQuery.each(JSON.parse('{ "asdf[zxcv]": "qwer" }'), function(index, value) {
var i = index;// i = "asdf[zxcv]"
var v = value;// v = "qwer"
var iOfInnerValue = (/\[(.*?)\]/g).exec(i)[1];// innerValue = "zxcv"
var iOfOuterValue = index.replace("["+(/\[(.*?)\]/g).exec(i)[1]+"]",""); // outerValue = "asdf"
});
You'll need to assign the data to a variable and then you can use Object keys to get the key which is the part before the :. Here's an example.
var j = { "asdf[zxcv]": "qwer" };
console.log(Object.keys(j)); //["asdf[zxcv]"]
console.log(j); //{asdf[zxcv]: "qwer"}

javascript create nested object variable for saving from dotted representation

I need to assign a value to nested object variable . The nested object variable will be given as
a.b.c
and the object will be given as
result
I need to create a variable
result[a][b][c]
so that i can bind value to this variable. Initially the result object only initialized as
var result = {}
This way you can do it
var a = 1, b = 2, c = "example";
var result = {};
result[a] = {};
result[a][b] = {};
result[a][b][c] = yourValue;

Categories

Resources