This question already has answers here:
Create an object with dynamic property names [duplicate]
(2 answers)
Closed last year.
I'm building a JS script in GoogleEarthEngine. I am automating the code for many year to get a vegetation index (Enhanced Vegetation Index (EVI)) for each year. The code I'm working itself is much more complex, that's why I just added one here for this question.(code here).
I'm trying to get the name of the layer in the key of the JS Object. So it would be:
buffer_size: 500
class: 0
EVI_2021_mean: MEAN_VALUE_FOR_THIS_YEAR
and have in the end, other columns following the same idea, only changing the year value in the Key of the object and its mean value for the Value of the object
The format itself is important to be that way so I can export to KML it afterwards and move on with further analysis.
Instead, what I'm getting is the string 'key' as the Key and the string EVI_2021_mean as the Value.
features: List (4 elements)
0: Feature 0 (Polygon, 3 properties)
type: Feature
id: 1
geometry: Polygon, 24 vertices
properties: Object (3 properties)
buffer_size: 500
class: 0
key: EVI_2021_mean
Obs: I'm setting the mean value inside the GetMean function:
var GetMean = function (fc, img, nome_img) {
print(nome_img);
var dict = [];
var ZS_mean = img.reduceRegion({
reducer: ee.Reducer.mean()
,geometry: POI
,scale: 30
});
dict.push({
key: nome_img+'_'+'mean',
value: ZS_mean.constant
});
print(ZS_mean);
var SetMean = function(f) {
return f.set(dict[0]);
};
return POI.map(SetMean);
};
You can set dynamic keys for JavaScript objects using the following notation:
const myKey = 'someKey'
const myObj = {
[myKey]: 'myValue'
}
console.log(myObj) // => { someKey: 'myValue' }
Additionally, you can set a dynamic property on an existing object like so:
const myKey = 'someKey'
const myObj = {}
myObj[myKey] = 'myValue'
console.log(myObj) // => { someKey: 'myValue' }
I'd suggest modifying your code to make dict an object (like dict = {}) and where you dict.push({ ... }) to do like dict[nome_img+'_mean'] = ZS_mean.constant.
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
access object through dot-syntax string path
(2 answers)
Access object child properties using a dot notation string [duplicate]
(13 answers)
Closed 4 years ago.
I am writing a function to convert array to List using Javascript.
If the input array is as below:
let inputArray = [1,2,3]
The output object should be like the below:
let outputList = {
value: 1,
rest: {
value: 2,
rest: {
value : 3,
rest: null } } }
I have the below function that accepts a nested object as its parameter and returns a string that represents where in the object, the property is null:
function getLastValue(object) {
let s = '';
if (object.rest) {
return s += '[rest]' + getLastValue(object.rest);
} else {
return s;
}
And the below function that converts an array to a list:
var list = {value: '', rest: null};
function constructList(arr) {
for (let prop of arr) {
let lastValue = getLastValue(list);
`${list}${lastValue}`.value = prop;
`${list}${lastValue}`.rest = null;
}
return list;
}
The constructList function fails to work as ${list}${lastValue} is a string. I need to convert the above from
'list[rest][rest]'
to
list[rest][rest]
Any help is appreciated!
This would be a great place to use reduceRight - construct the innermost object first, and have it be the new value of the accumulator, which is assigned to the next innermost object's rest property, and so on:
const constructList = arr => arr.reduceRight(
(rest, value) => ({ value, rest }),
null
);
console.log(
constructList([1, 2, 3])
);
To fix your original code, rather than constructing a string that attempts to refer to the nested object, iterate through the nested structure to find the innermost rest property instead, and return the object that doesn't contain a truthy rest property:
function getLastValue(obj) {
while (true) {
if (!obj.rest) return obj;
obj = obj.rest;
}
}
var list = {
value: '',
rest: null
};
function constructList(arr) {
for (let prop of arr) {
const nestedObj = getLastValue(list);
nestedObj.value = prop;
nestedObj.rest = {};
}
getLastValue(list).rest = null;
return list;
}
console.log(
constructList([1, 2, 3])
);
I need to iterate throug a object nodeIDs and find the key-indexes of specific values..
private getNodeIndexByID(nodeIDs, id) {
for (const [key, value] of Object.entries(nodeIDs)) {
if (id === value) {
return key;
}
}
}
the returned key is numeric
.. now I build a new object, where the key-indexes are saved
const index_source = this.getNodeIndexByID(nodeIDs, obj.source);
const index_target = this.getNodeIndexByID(nodeIDs, obj.target);
let my_obj = Object.create({}, { source: { value: index_source }, target: { value: index_target } });
out.push(my_obj);
now the values of out.source and out.target are typeOf STRING.. why? .. i mean, the array-index is numeric..
what am I missing? .. I need them to be numeric.
Keys of JavaScript objects are always (always!) strings, even if they were written to using numeric keys.
In other words,
x[0] = 1
is exactly the same as
x["0"] = 1
If you're numerating the key/value pairs of an object, you'll see string keys, because keys of JavaScript objects are always strings.
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
I have following json
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
I can access for instance the second element of the array like this:
dictionary[1].value
it returns 10 which is the score of the History subject.
What I'm looking for is the way so that I can access it by the word "History" itself, I mean I need a code like this:
dictionary["History"].value
How can I achieve that?
Ok, so here is a hack. You can use Array as an Object and insert any key you want. You can apply forEach to it and bind keys with properties like below.
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
dictionary.forEach(function(item) {
dictionary[item.key] = item;
});
console.log(dictionary["History"].value);
Note: This is just a Hack and will fail in case of duplicate entries.
Edited
Solution in case of duplicate keys
var dictionary = [{
"key": "Math",
"value": "20"
}, {
"key": "History",
"value": "10"
}, {
"key": "Chemistry",
"value": "12"
}, {
"key": "Chemistry",
"value": "13"
}]
dictionary.forEach(function(item) {
if (dictionary[item.key] && !Array.isArray(dictionary[item.key])) {
dictionary[item.key] = [dictionary[item.key]];
dictionary[item.key].push(item);
} else if (dictionary[item.key] && Array.isArray(dictionary[item.key])) {
dictionary[item.key].push(item);
} else {
dictionary[item.key] = item;
}
});
console.log(dictionary["Chemistry"]);
By using find() to iterate over your array.
From MDN Array.prototype.find():
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
const dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
const result = dictionary.find(item => {
// if this returns `true` then the currently
// iterated item is the one found
return item.key === 'History'
})
console.log(result)
There's more than one way to do this but this one is the most straightforward and succinct.
Try this:
var dictionary = [
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
];
function getValue(searchKey) {
var retVal;
dictionary.some(item => {
if (item.key === searchKey) {
retVal = item.value;
return true;
}
});
return retVal;
}
console.log(getValue('History'));
If goes through your array of objects and finds the object that matches its key to your searchKey and returns the result.
Or you can convert your array of objects into a single object and then reference it directly:
var dictionary = {};
[
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
].forEach(item => {dictionary[item.key] = item.value;});
console.log(dictionary.History);
I am fetching data from a text file and need help in making the information into an object..
Array:
['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
I need the values till \n in one object
expected result:
[{'celestine,timmy,celestinetimmy93#gmail.com,repeat 124}
{arun,mohan,reach#gmail.com,repeat 124213}
{jalal,muhammed,jallu#gmail.com,rave1231212321}
{vineeth,mohan,get,rave1231212321} ]
you can do in this way.
after applying splitting by '\n'
['celestine,timmy,celestinetimmy93#gmail.com,repeat
124\narun,mohan,reach#gmail.com,repeat
124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n'
]
you will get single one dimensional array.
["celestine,timmy,celestinetimmy93#gmail.com,repeat 124", "arun,mohan,reach#gmail.com,repeat 124213", "jobi,mec,mec#gmail.com,rave", "jalal,muhammed,jallu#gmail.com,rave1231212321", "vineeth,mohan,get,rave1231212321", ""]
Then looping it to get each individual record.
JS :
var test = ['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
var arrString = [];
test.forEach(function(val,key){
arrString = val.split('\n')
});
console.log(arrString);
arrString.forEach(function(val,key){
console.log(val.split(','));
})
In order to create an object, you'll need to format the string inside the curly braces as a dictionary of key value pairs. I am not sure what the keys or values are in your case. However if I assume that the key is "key" and the value is the text then:
var txt = 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n';
// Use trim, to remove the trailing whitespace, in your case a '\n'
// Use split to convert the text into an array of elements
var arr = txt.trim().split('\n');
// Use the map function to map each string to an object
var objects = arr.map(function(element) {
return { key: element};
});
Here is the output:
objects = [ { key: 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124' },
{ key: 'arun,mohan,reach#gmail.com,repeat 124213' },
{ key: 'jobi,mec,mec#gmail.com,rave' },
{ key: 'jalal,muhammed,jallu#gmail.com,rave1231212321' },
{ key: 'vineeth,mohan,get,rave1231212321' } ]
try this idea.
var x = "celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n";
var y = x.split("\n");
implement the remaining part. convert the array of arrays into array of objects using loops