Returning Key:Val pair from Object Array - javascript

I'm trying to create a dictionary of properties from an object array using arrow functions. So far I've tried a few variations of this:
let scVars = {};
scVars = sheetNamedRanges.map(x => (
{
{x.getName()}: {x.getRange().getValue()}
}
));
But I'm getting errors. I know this is a formatting issue but I'm a bit stuck so any help would be great

Array.map will return another Array but what you probably want is to create a new object. Try it like this:
let scVars = {};
sheetNamedRanges.forEach(x => {
scVars[x.getName()] = x.getValue()
});

Related

ES6 / Lodash, how to check if an object contains a specific value of given request?

With having an object like below, how would I know that a certain value, e.g: template:d51a08fe-fb60-4da0-841b-03a732f19576, existed in this object?
const obj= {
"5871": "template:d51a08fe-fb60-4da0-841b-03a732f19576",
"6993": "template:d07479ff-1172-4464-996d-32d6c7358979",
"5123": "template:280ac289-c726-4cb1-8a11-9ae1c987b399"
};
I was trying to use lodash some but this will need the property name, but I cannot provide the property here such as 5871
You can use Object.values() to get a list of all values in your Object. This will return an array of all values. Then you simply use includes function on the array to see if that values exists in the array.
const obj= {
"5871": "template:d51a08fe-fb60-4da0-841b-03a732f19576",
"6993": "template:d07479ff-1172-4464-996d-32d6c7358979",
"5123": "template:280ac289-c726-4cb1-8a11-9ae1c987b399"
};
const valueExists = Object.values(obj).includes("template:d07479ff-1172-4464-996d-32d6c7358979")
console.log(valueExists)
Lodash's _.includes() works with objects as well as arrays. In addition, you can use _.findKey() to, well, find the key:
const obj = {
"5871": "template:d51a08fe-fb60-4da0-841b-03a732f19576",
"6993": "template:d07479ff-1172-4464-996d-32d6c7358979",
"5123": "template:280ac289-c726-4cb1-8a11-9ae1c987b399"
};
const exists = _.includes(obj, 'template:d07479ff-1172-4464-996d-32d6c7358979')
const key = _.findKey(obj, v => v === 'template:d07479ff-1172-4464-996d-32d6c7358979')
console.log({ exists, key })
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Transforming array into a object in JavaScript

I am trying to convert an array into a javscript object that is designed to work with input checkboxes in AngularJS.
This is the input array that I get from my backend:
let selectedRolesDB = ['ADMIN', 'SECURITY'];
This is what my front-end expects:
let selectedRoles =
{
'ADMIN' : true,
'SECURITY': true
};
I tried different approaches such as angular.forEach but the problem is that I am not able to get the desired output:
angular.forEach(selectedRolesDB,(value, key) => {
this.selectedRoles.push({value : true });
});
Can anyone tell me how I best solve my problem so I end up with the array that my front-end expects?
JSFiddle
selectedRoles is not array, it is object. Init it as empty object:
let selectedRoles = {};
angular.forEach(selectedRolesDB,(value, key) => {
// use [] notation to add property with required name and value
selectedRoles[value] = true;
});
Use array.reduce :
let selectedRolesDB = ['ADMIN', 'SECURITY'];
const newArray = selectedRolesDB.reduce((accumulator, value) => {
accumulator[value] = true;
return accumulator;
}, {});
console.log(newArray)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce for documentation about it.
Probably it would be much better to use array's native 'forEach' method (it has a good browser support, see here Array forEach). Also this will be helpful if you decide to migrate your project into Angular2+, so avoiding usages of 'angular.someMethod' is a better approach.
This is a final solution:
const selectedRoles: {[key: string]: boolean} = {};
selectedRolesDB.forEach((value: string) => selectedRoles[value] = true);

Add a key to an object with keys of an existing array with objects

I've got an array of objects array = [object1, object2, ...], each of them has some keys object1 = { key1: 'value1', ... }. I want to add a key this way:
$rootScope.array[i].newKey = 'someValue'
But angular tells me that $rootScope.array[i] is undefined.
What I've noticed from console is that the objects get the new key but the console still says the same.
You should use less than and not less or equal than comparator.
$scope.init = function () {
for (i = 0; i < /* not <= */ $rootScope.meatTypes.length; i++) {
console.log("I am showing the meatypes:");
console.log($rootScope.meatTypes);
$rootScope.meatTypes[i].counter = '0';
counterOperations.setCounters(i, 0);
}
$rootScope.total = 0;
counterOperations.setTopCounter(0);
};
because when i equals $rootScope.meatTypes.length then $rootScope.meatTypes[i] is undefined.
You are trying to access a member of the array that does not exist.
You need to create a new object and push it onto the array:
$rootScope.array.push({'key1': 'someValue'});
You did not mention lodash, but when I see someone encounter an issue like this, I want to offer the recommendation of using lodash (or underscore.js).
With lodash, you would do something like so, using _.set, which defensively protects against your described issue by automatically adding the necessary elements in the path:
_.set($rootScope, ['array', i, 'newKey'], 'someValue');
This library, properly utilized, solves many issues that you can have with setting and getting variables, ase well as other super useful tools. It has been a major life-saver (and time-saver) for us on our projects.
Like this you can add
$rootScope.array[i] = {}; // first we should create an object on that array location
$rootScope.array[i]['newKey'] = 'someValue'; // then only we can add values
EDIT:
$scope.init = function () {
for (i = 0; i <= $rootScope.meatTypes.length; i++) {
console.log("I am showing the meatypes:");
console.log($rootScope.meatTypes);
**// This is needed**
$rootScope.meatTypes[i]={};// here we should tell that metaType[newItem] is an object other wise it treat it as undefined
$rootScope.meatTypes[i].counter = '0';
counterOperations.setCounters(i, 0);
}
$rootScope.total = 0;
counterOperations.setTopCounter(0);
};

AngularJS looping an object to build an array of objects

I am a newbie in JavaScript and AngularJS. I was trying out looping a object, get its key-value pair and then use it to build an array of new objects.
var actorMovie = {
"Leonardo DiCaprio" : "The Revenant",
"Christian Bale" : "The Dark Knight Rises",
"Sylvester Stallone" : "Rocky"
};
if(actorMovie){
var actorMovieArray = [];
angular.forEach(actorMovie, function(value, key) {
actorMovieArray.push ({key: {
"Movies": {
"Best Movie": value
}
}});
});
}
console.log(actorMovieArray);
This console log prints out the right values, but the key remains as 'key' and never updated to the actor's name as expected.
What am I doing wrong here? I tried searching for an answer but did not find any solution. Am I missing something?
I would do something like
angular.forEach(actorMovie, function(value, key) {
actorMovieArray[key]= {
"Movies": {
"Best Movie": value
}
};
});
In your code, javascript does not know that you want to evaluate the key variable to assign the property, and considers the key to be the key string.
As #Hugues pointed out, there is no way for JavaScript to know if you mean the key as literal or as variable, so the literal value is used.
Please be aware that the answer does not behave the same way as you wanted to in your question. Using the key as an array identifier has two drawbacks:
the order of the items when iterating over the keys cannot be retained
if there are two items having the same key (here the actor name), you will only get one in the result as you are overwriting some previously added value. (this is not really the case as your input already is an object literal so that duplicate keys are no concern, but could be a problem when switching to some other input, e.g. an array of items)
This could be okay for you as long as order doesn't matter and you know your keys are unique. If you want the structure as defined in your question, please consider the following snippet:
function buildItem(value, key) {
var res = {};
res[key] = {
"Movies": {
"Best Movie": value
}
};
return res;
}
if(actorMovie){
var actorMovieArray = [];
angular.forEach(actorMovie, function(value, key) {
actorMovieArray.push(buildItem(value, key));
});
}
Try out this jsbin: http://jsbin.com/luborejini/edit?js,console
I would use Object.keys and Array.forEach on the resulting array. And I would also embrace Javascript's functional nature. That way you could easily pull out the creator function into factory mapping libraries for your api json data.
if(actorMovie){
var actorMovieArray = [];
Object.keys(actorMovie).forEach(function(actor){
actorMovieArray[actor] = function(){
return {
Movies: {
BestMovie: actorMovie[actor]
}
};
}();
});
}
I would also recommend not using the actor name as the key in the array. I would rather map it to a model structure, it will make your views / controllers cleaner and easier to understand:
if(actorMovie){
var actorMovieArray = [];
Object.keys(actorMovie).forEach(function(actor) {
actorMovieArray.push(function(){
return {
Actor: actor,
Movies: {
BestMovie: actorMovie[actor]
}
};
}());
});
}
This will drive you into more concise view models, and set you up for easy refactoring once your structure is in place. It will also make testing easier, at least in my opinion.

JavaScript Two-Dimensional array is undefined

I was trying to resolve my error with other answers but just fail. I have this simple example of what I think is two-dimensional array but it keeps returning me undefined error.
var city = 'London',
country = 'England';
var locate = [];
locate['London']['England'] = ['Jhon','Mike'];
for (i = 0; i < locate[city][country].length; i++) {
console.log(locate[city][country][i]);
}
jsbin http://jsbin.com/pixeluhojawa/1/
what am I doing wrong in this example, I would appreciate your help.
Before you can assign a value to locate['London']['England'], you'll have to make sure that locate['London'] is an object:
var locate = {};
locate['London'] = {};
locate['London']['England'] = ['Jhon','Mike'];
Notice how I used an object literal ({}) instead of an array literal ([]). Arrays don't support string keys like this. You'll need to use objects instead.
You can also declare it like this::
var locate = {
London:{
England:["Jhon","Mike"]
}
}

Categories

Resources