JavaScript request object- convert key as a variable to string - javascript

I'm a programming beginner.
API post call accepts object variable (derived from variable) as a string as follows
"option":
{
"235": “30”
},
{
"238": “32”
}
My code angular 6
option = [];
---
this.option.push({
[option.product_option_id]: $event
});
which result
option = [ {
235: 30
}]
but need this variable in double-quoted "235".
please help

but need this variable in double-quoted "235"
By which you mean that you need it to be a string.
Don't worry, it is. When you use a number as a property name, it's converted to a string automatically. Property names can only be strings or Symbols, so things that aren't strings or Symbols get converted to string:
class Example {
constructor() {
this.option = [];
const option = {
product_option_id: 42
};
const $event = {};
this.option.push({
[option.product_option_id]: $event
});
const pushed = this.option[0];
for (const key of Object.keys(pushed)) {
console.log(`${key}: ${typeof key}`);
}
}
}
new Example();
That said, the expression within the [] of a computed property name is just that: an expression. So if you wanted to be explicit, you could use String there:
option.push({
[String(option.product_option_id)]: $event
});

Related

Pass an array of objects to another function onclick

I just want to ask how to pass an array of objects to another function.
I have a function
function btnB(weekly) {
console.log(weekly);
}
function btnA() {
const array = [{ abc : 123 }, { def : 456 }]
div.innerHTML = `<div onclick="btnB(${array[0]});"`;
divList.appendChild(div);
}
btnA();
And I'm getting an error
Uncaught SyntaxError: Unexpected identifier
You can't substitute an object like that in a template literal. It converts the object to a string, which returns [Object object].
Use JSON.stringify() to convert it to an object literal.
function btnA() {
const array = [{ abc : 123 }, { def : 456 }]
div.innerHTML = `<div onclick='btnB(${JSON.stringify(array[0])});'`;
divList.appendChild(div);
}
You also should use single quotes around the onclick value, because JSON uses double quotes around the object keys.
function btnB(weekly) {
console.log(weekly);
}
function btnA() {
const array = [{ abc : 123 }, { def : 456 }];
const div = document.createElement('div'); // delete if useless
div.addEventListener('click', () => {
btnB(array[0])
});
divList.appendChild(div);
}
I'm assuming the [0] is part of your attempt to solve this, but based on the question asking to pass an array of objects to the click handler, I'll refer to that instead.
Inline event handlers are deprecated and problematic anyway, but using them in HTML generated by JavaScript completes the circle in an absurd way. It would be a lot easier and more robust (and secure) to attach the click handler via JavaScript as well, as follows:
const array = [{ abc: 123 }, { def: 456 }]
div.innerHTML = '<div></div>' // Just the inner div without onclick
div.firstElementChild.addEventListener('click', () => btnB(array))
divList.appendChild(div)

How to get value of string which has list of arrays from json object

I have this json
var json = {
"I:5.3": {
"conf": {
"name": "Jack"
}
}
}
and this string
var str = '["I.5.3"]["conf"]'
How can get str value from json like
json["I.5.3"]["conf"]
I have json object and str and I have to extract something like
json[str] = json["I.5.3"]["conf"]
Your title suggests you would like to get:
The value of a string.
Which has a list of Array's.
From a JSON object.
However, all your code shows is a Plain JavaScript object. No arrays to be seen... and the only string value I can find is "Jack".
Jack would be extracted like, json["I.5.3"]["conf"]["name"].
Or via dot notation =>
const obj = json["I.5.3"];
const nameValue = obj.conf.name; // => Jack
You have 2 ways(at least that's what's in coming through my mind now):
1st way
var json = {
"I:5.3": {
"conf": {
"name": "Jack"
}
}
}
var str = '["I:5.3"]["conf"]'
var scr_line = 'json'+str;
var target = eval(scr_line);
console.log(target);
2nd way:
var json = {
"I:5.3": {
"conf": {
"name": "Jack"
}
}
}
var str = '["I:5.3"]["conf"]';
let ret = getVal(json, str);
console.log(ret);
function getVal(obj, path){
var regex = /\["(.*?)"\]/mg;
let m;
while ((m = regex.exec(path)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(typeof obj[m[1]] !== 'undefined') obj = obj[m[1]];
else return obj[m[1]];
}
return obj;
}
I would prefer the second because it checks if the property on the object exists
You would have to split the string up into separate parts, I believe.
var str = '["I.5.3"]["conf"]';
var identifiers = str.split('][');
// identifiers would be an array like:
// ["I.5.3", "conf"]
var person = json[identifiers[0]][identifiers[1]];
// person = {
// "name": "Jack"
// }
String.prototype.split() allows you to separate parts of a string out into an array. Checkout the MDN docs to learn more about that particular method.
This specific answer expects that there will always be the properties you split, though and will error out if one is missing. For something a little safer, I would suggest checking to see if that object contains the property you're expecting before trying to access it.
var str = '["I.5.3"]["conf"]';
var identifiers = str.split('][');
try {
var myVal;
// Let's check if the property exists.
if (Object.prototype.hasOwnProperty.call(json, identifiers[0]){
myVal = json[identifiers[0]];
if (Object.prototype.hasOwnProperty.call(myVal, identifiers[1]){
myVal = myVal[identifiers[1]];
}
}
} catch(error) {
// One of the properties didn't exist or something went wrong in the try
// block above.
}
EDIT:
The follow would format your string specifically to meet the match to become an array. If there were single quotes or double quotes anywhere in each array item, this would fall through, so be aware of that.
var myArray = str.slice(2, -2).split('][').map(function(item) {
return item.replace('"', '');
});
String.prototype.slice() extracts a section of a string and returns it as a new string, without modifying the original string.
Then the split method separates it into different array items. Then we iterate over each item in the array and remove additional ". Just to say again, this will fall apart if the original string looks like ['one']['two']. This would also not be reliable if the string looks like ["can't"]["won't"]. So just be aware of that in your particular case. If you're positive that the string will always meet the format you have above, then you can rely on this.

Creating object with dynamic keys [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.
Heres the situation:
I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this:
[ { key: '1' }, { key: '1' } ]
(.map() returns an array of objects fyi)
I need key to actually be the string from this.attr('name').
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).

How to declare nested objects in JavaScript?

I'm trying to create an object that contains an object, so think of it as a dictionary:
var dictionaries = {};
dictionaries.english_to_french =
{
{english:"hello",french:"bonjour"},
{english:"i want",french:"je veux"},
{english:"bla",french:"le bla"}
};
but it gives the error Uncaught SyntaxError: Unexpected token {
what am I doing wrong?
Thanks !
Edit
I'm sorry that I did not clarify what I want to do.
Edited the code above.
You're trying to give your object a property, and that property will be a single object:
dictionaries.english_to_french =
{english:"hello",french:"bonjour"}
;
You don't need the extra { }. You could declare the whole thing at once:
var dictionaries = {
english_to_french: {
english: "hello", french: "bonjour"
}
};
I would suggest that a better format for your dictionaries might be:
var dictionaries = {
english_to_french: {
"hello": "bonjour",
"chicken": "poulet", // ? something like that
"Englishman": "rosbif"
}
};
That way you can look up words directly without having to search. You could then create the reverse dictionary from that:
dictionaries.french_to_english = function(dict) {
var rv = {};
for (var eword in dict)
rv[dict[eword]] = eword;
return rv;
}(dictionaries.english_to_french);
In order to nest two or more objects, the objects need to have an attribute assigned to them. For example,
{
"hello":{
"english":"hello",
"french":"bonjour",
"portuguese":"ola"
},
"good day":{...},
"how are you":{...}
}
"hello" at the beginning of the object would be the attribute. Then the object is its value. So that way you can access the object by accessing its attribute. Just putting an object in an object does not work. That's why you're getting your error.

object Key in javascript class/dictionary?

I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object

Categories