How to destructure obj[arr[0]] = arr[1] - javascript

Given the following code eslint throws a prefer-destructuring error at me:
const params = {};
const splitted = 'key=value'.split('=');
params[splitted[0]] = splitted[1];
How can I use destructuring in the third line?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Try the below example, it assign value at zero index to key variable and value at first index to value variable.
const params = {};
const [key,value] = 'key=value'.split('=');
params[key] = value;
console.log(params);

Related

How to use string varaible value as key name in object in Typescript

In Typescript I would like the myObj variable to be:
{'key01': 'value01'}
So I go ahead with:
let keyName = 'key01';
let myObj = {keyName: 'value01'};
console.log(myObj);
But the resulting variable is
{ keyName: 'value01' }
Can I use the value of the keyName variable to use as the key name for the variable myObj?
If you don't want to waste space with an extra line of code for defining the main object and then defining the custom key, you can use bracket notation inline.
let keyName = 'key01';
let myObj = { [keyName]: 'value01' };
console.log(myObj);
You can use the bracket notation property accessor:
let keyName = 'key01';
let myObj = {};
myObj[keyName] = 'value01';
console.log(myObj);
For TypeScript, use:
let keyName = 'key01';
let myObj:any = {};
myObj[keyName] = 'value01';
If you want to change the value of your object using the variable keyName you can use the following.
let keyName = "newValue";
let myObject = {keyName: "oldValue"}
myObject.keyName = keyName
console.log(myObject)

ESLint error: 'value' is never reassigned use 'const' instead

I'm adding ESLint to my Node project and cannot figure out how to change this code to work properly:
const connection = {};
for (let [prop, value] of connectionString) {
prop = prop.split(' ')[0];
connection[prop] = value;
}
I'm getting error:
'value' is never reassigned. Use 'const' instead.
Rather than reassigning prop, create a new variable for the first word. That way, both prop and value can be declared with const:
const connection = {};
for (const [prop, value] of connectionString) {
const firstWord = prop.split(' ')[0];
connection[firstWord] = value;
}
Most of the time, clean readable code can work just fine without ever reassigning a variable. Best to only reassign an existing variable when you absolutely have to - that's a big part of why the rule exists, to prod you to use const (and produce more readable code as a result).
You could also achieve it without the intermediate variable:
const connection = {};
for (const [prop, value] of connectionString) {
connection[prop.split(' ')[0]] = value;
}

How to access a value within a JSON Object

I have the following JSON object notation:
[{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}]
and am unsure how to only access the "cname" value alone in JavaScript, i.e. I just require:
"www.fred.com.au"
I have tried res[0].cname but this didn't seem to work.
If you have
let object = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
then you can get that URL value via
let url = object[0]["getCname('mail.fred.com.au')"][0].cname;
The outer object is an array, and the value of the property with the long strange name is also an array, hence the [0] in two places.
This is a bit cludgy but if you don't know the 'getCname' key you can do:
let res = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
let key = Object.keys(res[0])[0];
let cname = res[0][key][0].cname;
Try these
var res = [{"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]}];
res[0] ;// returns Object {"getCname('mail.fred.com.au')":[{"cname":"www.fred.com.au"}]};
res[0]["getCname('mail.fred.com.au')"] ;//returns Array [{"cname":"www.fred.com.au"}];
res[0]["getCname('mail.fred.com.au')"][0].cname ;//returns "www.fred.com.au"

There is any rule for define a json key in JavaScript?

I'm learning JavaScript and I was looking for a while about this and I have not got any answer about this. My question is if there is any rule to define a JSON key in JavaScript.
For example, in python there is a rule defining dict and is All the keys must be of an immutable data type such as strings, numbers, or tuples.
var json = {};
json[""] = "White space";
json[" "] = "Two white space";
var emptyJSON = {};
var emptyArray = [];
function a (){}
json[a] = "Function";
json[emptyJSON] = "Json";
json[emptyArray]= "Array";
//I don't know why this property whit an empty array does not appear when I console the json
console.log("Print the entire object =>", json);
//But it appears when I console the specific property
console.log("Print empty array property =>", json[emptyArray]);
Object keys are strings. Anything that is not a string is converted to a string.
var obj = {};
obj[1] = 1;
console.log(obj["1"]);
obj[{}] = 2;
console.log(obj["[Object object]"]);
obj[[1, 2]] = 3;
console.log(obj["1,2"]);

variable as index in an associative array - Javascript

I'm trying to create an associative array, create an empty array, and then add a (indexName -> value) pair:
var arrayName = new Array;
arrayName["indexName"] = value;
// i know i can also do the last line like this:
arrayName.indexName = value;
When I assign the value to the indexName I want indexName to be dynamic and the value of a variable. So I tried this:
arrayName[eval("nume")] = value;
Where:
var var1 = "index";
var var2 = "Name";
var nume = '"' + var1 + var2 + '"';
but: alert(arrayName["indexName"]); doesn't return "value"... it says "undefined"
Is there something I’m missing? (I’m not familiar with eval() ); if the way I’m trying is a dead end, is there another way to make the index name of the associative array value dynamic?
At first I don't think you need a real array object to do what you need, you can use a plain object.
You can simply use the bracket notation to access a property, using the value of a variable:
var obj = {};
var nume = var1 + var2;
obj[nume] = value;
Array's are simply objects, the concept of an "associative array" can be achieved by using a simple object, objects are collections of properties that contain values.
True arrays are useful when you need to store numeric indexes, they automatically update their length property when you assign an index or you push a value to it.
You would use objects to do that:
var hash = {}
hash["foo"] = "foo";
hash.bar = "bar";
// This is the dynamic approach: Your key is a string:
baz = "baz"
hash[baz] = "hello";
To iterate, just use a for loop or $.each() in jQuery.
use arrayName[var1+var2]
Note that arrayName.var is the same as arrayName["var"] -- it's just syntactic sugar. The second form is mostly used when dealing with the kind of problems that you are facing - dynamic object keys, and keys that are not alphanumeric (think of arrayName[".eval()"]; this is a perfectly legal object key that has nothing to do with the javascript eval() function)
Are you looking for variableName = 'bla'+'foo'; arrayRef[variableName] = 'something'; ?
And even so, you should use an object literal instead. x = {}; x[variablename] = 'blah';
You want a plain object with the same bracket notaiton here, like this:
var arrayName = {};
arrayName["indexName"] = value;
Indeed, there was no need for an array object, a simple object did the job; further more an array introduced the need to use quotes inside the square brackets obj["var1 + var2"] to access the object property's value and not the value associated with an index (i think); the quotes transformed "var1 + var2" into a string. Using a simple object eliminated the need for quotes, so I can use obj[var1 + var2], wich worked :)
Thanks everyone !
I did something like like following;
let parentArray = [];
let childArray = [1, 2, 3];
childArray.name = 'my-array-1';
parentArray.push(childArray);
To access that by name in ES6;
parentArray.filter(x => x.name == 'my-array-1');

Categories

Resources