change key's value across multiple objects at once in JS - javascript-objects

I have multiple objects that all have the same keys lets say each object has: name and position. The first object will start with position=0. The second object would have position=1. The third object would have position=2 and so on until we get to the 10th object that would have position=9.
I need a way to subtract 1 from every objects position (with only possible values being 0-9 so that 0-1=9)
Looking for a solution that handles all of them mathematically at once, not just re-writing out new values to assign to each key individually.

Suppose you have an array of JavaScript objects, you could use map:
var newObjs = objects.map(function (object) {
object.position = (object.position === 9 ? 0 : object.position--);
return object;
});
A better approach would be:
objects.forEach( function (object) {
object.position--;
object.position = object.position < 0 ? 9 : object.position;
});

Related

How can do array map inside methods in vuejs

How can ı equalize my array ıd and my value ıd and access value.name I didn't do it
This is my code:
activity(val) {
var act = this.items.map(function (val) {
if (element.ActivityID== val) {
return element.ActivityName
}
return act
});
Perhaps this?
activity (val) {
const activity = this.items.find(item => item.ActivityID === val)
return activity && activity.ActivityName
}
This just finds the item with the corresponding ActivityID and then returns its ActivityName.
Your original code contained several possible mistakes:
Two different things called val.
element doesn't appear to be defined.
The return act was inside the map callback. The activity method itself wasn't returning anything.
Not really clear why you were using map to find a single item. map is used to create a new array with the same length as the original array with each item in the new array determined by the equivalent item in the original array. It 'maps' the items of the input array to the items in the output array.

How to push object into an array? in Angular 7

I am pushing an object into an array but cannot do it?
I'm doing it like this
this.passData = this.tribeForm.value;
var id = {"tribe_id": 1}
this.passData.push(id)
This is the value in the tribeForm
I also tried
var id = {tribe_id: 1}
and
this.passData.splice(0,0, id)
and
this.passData = Array.prototype.slice(id)
and
this.passData.concat(id)
but it all ends up with
TypeError: this.passData.push/splice/concat is not a function
The question is not that clear, But I understood you are manipulating form data, value of form data returns an Object, Not an array. Objects in JavaScript are represented as key-value pairs, (or attribute-value) pairs.
Example :
var object = {
name : "Jhon",
grade : 12,
gpa : 8.12
}
It is just a collection of key-value pairs, push(), concat() and other methods are supported only for Arrays not for Objects. You can achieve whatever you want simply by creating a new key/attribute and assigning the value to it.
this.passData = this.tribeForm.value
this.passData['tribe_id'] = 1
//or, Objects can also contain nested object
this.passData['someKey'] = {'tribe_id' : 1}
You can create an empty array and push objects to it
Example :
var exampleArray = []
exampleArray.push({'tribe_id' : 1})
Now, it works because exampleArray is an Array not JS object.
Thanks for A2A
First, you need to understand the error:
TypeError: this.passData.push/splice/concat is not a function
Push/splice/concat is functions for Array and because of that the console is yelling at you that the passData is not an Array.
Make sure your passData is an Array and you will able to do so.

Angular 2 / Typescript - how to check an array of objects to see if a property has the same value?

This question does it in Javascript, but I would have thought in Typescript I could do some kind of map/filter operation to do the same thing.
I have an array of objects called Room. Each Room has a property called Width (which is actually a string, eg '4m', '5m', '6.5m').
I need to check the entire array to see if all the widths are the same.
Based on that question I have this, but I was wondering if TypeScript has something better:
let areWidthsTheSame = true;
this.qp.rooms.forEach(function(room, index, rooms) {
if (rooms[index] != rooms[index+1]) areWidthsTheSame = false;
});
Any ideas?
FYI the linked question has a comment that links to these performance tests, which are interesting in the context of this question:
This can be done in the following way:
const widthArr = rooms.map(r => r.width);
const isSameWidth = widthArr.length === 0 ? true :
widthArr.every(val => val === widthArr[0]);
We first convert the rooms array to an array of widths and then we check if all values in widths arrays are equal.

Comparing array with array of hashes and outputing new array of hashes

I have an array of subscription instances #subscription_valids and an array of subscribed player that look like that :
array_subscribed_players = [{"name0" => "link1"}, {"name1"=>"link2"}, {"name2"=>"link3"}....]
What I need to do is : for each subscription in #subscription_valids :
#subscription_valids.each do |subscription|
I need to check if subscription.user.full_name or if subscription.user.full_name_inversed matches a key in one of the hashes of array_subscribed_player (in the exemple "name0", "name1" or "name2").
If it matches then I should store the relevant subscription as key in a hash in a new array and extract the relevant link as value of this hash. My final outpout should be an array that looks like this :
[{subscription1 => "link1"}, {subscription2 => "link2}, ...]
else if the subscription.user.full_name doesnt match i'll just store the subscription in a failure array.
How can I achieve this result ?
See http://ruby-doc.org/core-2.2.3/Hash.html
A user-defined class may be used as a hash key if the hash and eql?
methods are overridden to provide meaningful behavior. By default,
separate instances refer to separate hash keys.
so I think you should override your .eql? method in #subscription_valids to something meaningful (like a unique string)
I can't think for a Array method so you can go like:
demo
results = []
failures = []
#subscription_valids.each do |subscription|
array_subscribed_players.each do |player|
if player.keys.first == subscription.user.full_name || player.keys.first == subscription.user.full_name_inversed
results << { subscription => player[player.keys.first] }
else
failures << subscription
end
end
end
You can try the following:
valid = array_subscribed_players.select{|x| #subscription_valids.map(&:name).include?(x.keys.first)}
Demo
If you need to store both valid and invalid values somewhere:
valid, invalid = array_subscribed_players.partition{|x| #subscription_valids.map(&:name).include?(x.keys.first)}

as3 check for 2 objects with same property in array

I have an array, lets call it _persons.
I am populating this array with Value Objects, lets call this object PersonVO
Each PersonVO has a name and a score property.
What I am trying to do is search the array &
//PSEUDO CODE
1 Find any VO's with same name (there should only be at most 2)
2 Do a comparison of the score propertys
3 Keep ONLY the VO with the higher score, and delete remove the other from the _persons array.
I'm having trouble with the code implementation. Any AS3 wizards able to help?
You'd better use a Dictionary for this task, since you have a designated unique property to query. A dictionary approach is viable in case you only have one key property, in your case name, and you need to have only one object to have this property at any given time. An example:
var highscores:Dictionary;
// load it somehow
function addHighscore(name:String,score:Number):Boolean {
// returns true if this score is bigger than what was stored, aka personal best
var prevScore:Number=highscores[name];
if (isNaN(prevScore) || (prevScore<score)) {
// either no score, or less score - write a new value
highscores[name]=score;
return true;
}
// else don't write, the new score is less than what's stored
return false;
}
The dictionary in this example uses passed strings as name property, that is the "primary key" here, thus all records should have unique name part, passed into the function. The score is the value part of stored record. You can store more than one property in the dictionary as value, you'll need to wrap then into an Object in this case.
you want to loop though the array and check if there are any two people with the same name.
I have another solution that may help, if not please do say.
childrenOnStage = this.numChildren;
var aPerson:array = new array;
for (var c:int = 0; c < childrenOnStage; c++)
{
if (getChildAt(c).name == "person1")
{
aPerson:array =(getChildAt(c);
}
}
Then trace the array,

Resources