destructuting is not happening with string from array [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 months ago.
i am trying to destructure an array and return an object. but the key is not working inside the object. but outside of the object destructuring happening smoothly.
let [key, value] = ["b", 2];
let object = { key: value };
console.log(object); // {key: 2}
console.log(key, value)// b, 2

Bracket notation!
To use a variable as a key in objects...
Because when creating an object, the parser interprets the string in front of : as a key.
The string after the : for sure has to be a variable if it isn't wrapped with quotes to specify a string.
So for the key, it does not know you want to use the variable named like that string.
How to tell it is the brackets use.
let [key, value] = ["b", 2];
let object = { [key]: value }; // Brackets around the key variable
console.log(object); // {"b": 2} As expected...
console.log(key, value)// b, 2

Related

Accesing items with custom keys in object [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 1 year ago.
I have object like this:
{
"first" : "value1",
"second" : "value2"
}
I want to access both values in for cycle. Order of getting values doesn't mind. Usage is for something like value = value + "something". How to acces values which key names I don't know? Of course I can get keys from helping array like:
var keys = ["first", "second"];
And then get them by index and with them get value1 and value2 from my original array. Is there some better way? For some reason foreach doesn't work either.
Javascript has a for ... in to loop through keys
for (var key in object) {
console.log(object[key])
}
To access both values:
const data = {
"first": "value1",
"second": "value2"
};
// (1) for-loop
for (const [key, value] of Object.entries(data)) {
console.log("for-loop:", key, value);
}
// (2) Array.prototype.forEach
Object.entries(data).forEach(([key, value]) => {
console.log("Array.prototype.forEach:", key, value);
});
If you just want the keys and values separately in an array you can do the following:
var data = {
"first" : "value1",
"second" : "value2"
}
var keys = Object.keys(data)
var values = Object.values(values)
Printing them out individually would give you:
console.log(keys)
Output: ["first", "second"]
console.log(values)
Output: ["value1", "value2"]

How to extract Key or the first value of JSON parsed object [duplicate]

This question already has answers here:
Javascript how to parse JSON array
(10 answers)
Closed 1 year ago.
I have parsed an object into JSON. When I use the console log, it shows like this.
{14: "Cromwell"}
How can I get the key value from it.
Use a for loop to split each key-value pair, like this:
var data = {1:'a', 2:'b', 3:'c'};
for(var key in data){
console.log('key = ' + key + ', value = ' + data[key]);
}
Let's say your variable is named "myObj", so you'll have:
const myObj = {14:"Cromwell"};
To access the key, you can use the Object.keys method:
const myKey = Object.keys(myObject).pop();
This will return you "14" as a result, which is a string equivalent of the key you're trying to obtain. To convert it to an integer, just use the parseInt() method.
To get the value from that object, then you can do:
const myValue = myObject[myKey];

What does this Javascript object syntax means? It has a key (a string) and a value (object)

I am following a tutorial on Youtube about importing data into existing todo list component in React.
If you look at the code below, at the const data object, there are two keys namely lists and listIds. There are two parts which I don't understand.
Why is the key "list-1" a string while the value {id: "list-1",title: "Todo",cards,}
is a normal object? I could not figure out this syntax. If it's JSON format, both key-value should be a in quotation marks.
Is the listIds: ["list-1"] just a normal key-value pair which has an array as its value? If so, why does it has the same name as the one from the initial lists keys? Is this a Destructuring method from ES6?. I just cannot understand the syntax.
const cards = [
{
id: "card-1",
title: "Learning how to cook",
},
{
id: "card-2",
title: "Making sandwich",
},
{
id: "card-3",
title: "Taking the trash out",
},
];
const data = {
lists: {
"list-1": {
id: "list-1",
title: "Todo",
cards,
},
},
listIds: ["list-1"],
};
export default data;
Because "list-1" contains a minus sign and that would be an error for an identifier name. It would be like trying to subtract 1 from "list" and use the expression as a key.
listIds : ["list-1"] is a normal JS key-value expression with a key to the left of : and an array with a single string value to the right.
Object data.lists looks like it contains various sub-objects, each having an ID and listIds is just an array containing all the keys in lists. In your example there is one sub-object and correspondingly, one key in listIds.
One more thing: In a JSON string, keys to the left of : must be in double quotes, however this is a Javascript object, and Javascript objects can have keys without double quotes as long as each key is formatted as a regular Javascript variable, as well as values to the right of : that many times cannot be represented in a JSON string, such as functions for example.
I just thought I'd add a little summary here about declaring key/value pairs in an object declaration. When you declare an object property as in:
let obj = {prop: value};
the left hand side of the property declaration is the property name. There are three possible syntaxes allowed for that:
Plain String - No Quotes
// no quotes - this is allowed when the property name
// doesn't contain any reserved characters
let obj = {prop: value};
Quoted String
// quotes - this is always allowed, but is required when the property name
// does contain reserved characters like a "-" such as your example of "list-1"
let obj = {"prop": value};
Brackets around a variable name
// computed property name. This is used when the property name you want to use
// is in a variable
let someVar = "prop";
let obj = {[someVar]: value};
All three of these options above create the exact same key/value pair in that object.
The right hand side of the prop: value pair can be any Javascript expression like these:
let obj = {prop: 3}; // a number
let obj = {prop: "foo"}; // a string
let obj = {prop: value}; // value from some variable
let obj = {prop: [1,2,3]}; // an array
let obj = {prop: resultFromCallingFunc()}; // the result from calling some function
let obj = {prop: {greeting: "hello"}}; // another object
let obj = {prop: 3 + 4}; // any expression

How to get key by value in object of keys of arrays in Javascript? [duplicate]

This question already has answers here:
Dynamically get 'Key' with 'Value' in javascript
(3 answers)
Closed 3 years ago.
How to get the key from object of keys of array in java script?
var object = { "a" : [], "b" : ["S","W"] "c" : ["N","E"]}
How can i get the key by the value of "S" in java script?
Object.keys()
Object.keys() will create an array of keys for the object that is in variable object
find() will find the matching key that matches the condition. In your case, matching the toSearch text inside the array values of that key, for which you can use includes() or even indexOf(toSearch) !== -1
var object = { "a" : [], "b" : ["S","W"], "c" : ["N","E"]};
var toSearch = 'S';
var key = Object.keys(object).find((key) => object[key].includes(toSearch));
console.log(key);
You can also use another way using Object.entries() like:
var object = { "a" : [], "b" : ["S","W"], "c" : ["N","E"]};
var toSearch = 'S';
var key = (Object.entries(object).find(([key, value]) => value.includes(toSearch)) || [])[0];
console.log(key);
You can create a function and pass the object & the val. Inside the function iterate the object using for..in and check if the value contains the searched text. If so then push the key in an array & return it. This returned array will contain all the key name which have the searched text in it's value array
var object = {
"a": [],
"b": ["S", "W"],
"c": ["N", "E", "S"]
}
function getKey(obj, val) {
let keyArr = [];
for (let keys in obj) {
if (obj[keys].includes(val)) {
keyArr.push(keys)
}
}
return keyArr;
}
console.log(getKey(object, 'S'))

Get the first key name of a JavaScript object [duplicate]

This question already has answers here:
How to access the first property of a Javascript object?
(23 answers)
Closed 3 years ago.
Let's assume we have the following JavaScript object:
ahash = {"one": [1,2,3], "two": [4,5,6]}
Is there a function that returns the first key name for the given object?
From the example above I want to get one as a result of that function.
In Javascript you can do the following:
Object.keys(ahash)[0];
You can query the content of an object, per its array position.For instance:
let obj = {plainKey: 'plain value'};
let firstKey = Object.keys(obj)[0]; // "plainKey"
let firstValue = Object.values(obj)[0]; // "plain value"
/* or */
let [key, value] = Object.entries(obj)[0]; // ["plainKey", "plain value"]
console.log(key); // "plainKey"
console.log(value); // "plain value"
There's no such thing as the "first" key in a hash (Javascript calls them objects). They are fundamentally unordered. Do you mean just choose any single key:
for (var k in ahash) {
break
}
// k is a key in ahash.
Try this:
for (var firstKey in ahash) break;
alert(firstKey); // 'one'
If you decide to use Underscore.js you better do
_.values(ahash)[0]
to get value, or
_.keys(ahash)[0]
to get key.
With Underscore.js, you could do
_.find( {"one": [1,2,3], "two": [4,5,6]} )
It will return [1,2,3]
I use Lodash for defensive coding reasons.
In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.
A "fully defensive" approach with Lodash would use both keys as well as get:
const firstKey = _.get(_.keys(ahash), 0);
you can put your elements into an array and hash at the same time.
var value = [1,2,3];
ahash = {"one": value};
array.push(value);
array can be used to get values by their order and hash could be used to get values by their key. just be be carryfull when you remove and add elements.

Categories