using map to reformat objects in Array in JAVA SCRIPT - arrays

const kvArray = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 },
];
const reformattedArray = kvArray.map(({ key, value}) => **({ [key]: value }));**
// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],
// kvArray is still:
// [{key: 1, value: 10},
// {key: 2, value: 20},
// {key: 3, value: 30}]
code
Java Script so In Java Script we have objects and are denoted by {}. eg {key:1, value:10} so in objects we have key value pair like key:1. key is named as key and its value is 1. similarly for value :10 key is named as value and its actual value is 10. and when we need to know the value of key we use [key]. So in above example where we have defined reformattedArray in the end we have used ({ [key]: value })) so why the value is not in [].
can some one help me with this?
when we need value from the Key we are using brackets[] but when we need the value from the element value why are we not using brackets.
what i know is when we need to get value we always use []
the entries with in array are objects { key: 1, value: 10 } objects are represented as {key;value} pair so in { key: 1, value: 10 } for there are two elements key:1 and value:10 keeping in mind anything in objects are represented as {key:value} so in key:1 key is named as key and its value is 10 similarly key and value in {value:10} are value and 10. So when we need to get the value of any key in object we use [key] which will return us the value of that key and should be same for [value] we will get value. so which in above example we are not using [ ] notation while retriving value
please help.
[1]: https://i.stack.imgur.com/F6zJ2.png

Related

Adding data to complex state in react reducer

I have a react reducer that manages the following kind of state
const exampleState: INote[][] = [
[
{ x: 3, y: 5, value: '4' },
{ x: 3, y: 6, value: '4' },
],
[
{ x: 7, y: 3, value: '4' },
{ x: 8, y: 5, value: '7' },
{ x: 8, y: 5, value: '6' }
],
];
So a 2D array that contains arrays of a specific type of object. For some reason I can't figure out how to update this kind of state. I want to specifically be able to add a new instance (without mutating original state) of INote to a specific nested array. How can I achieve this? The index of the array I need to add the object to is in my reducers action object
Well, the obvious ways would be to update this state immutably, for instance, let's say I have a ADD_NOTE action, it could look something like that:
{type: "ADD_NOTE", payload: { item: INote, index: number }}
And then, an example return statement of the reducer for this action would be:
return state.map((arr, i) => i === index ? [...arr, item] : arr)
This will update the array, and will add item to the end of the array with the provided action index.
Another solution that might make your life easier is to use help libraries such as https://github.com/kolodny/immutability-helper or https://github.com/immerjs/immer
You need to use an array of objects instead of array of arrays so you can add an identifier such as an id to each object so you can update that specific object based on its id

In an array of obects watched with Vue-watch, how to get index of object that was changed?

I have an array of objects, like this:
myArray: [{
name: "First",
price: 10,
rebate: 5,
listPrice: 15,
outcome: 0
},{
name: "Second",
price: 11,
rebate: 5,
listPrice: 16,
outcome: 0
}
I want to recalculate the outcome-value whenever any of the other values in the same object change.
I already have a setup like this, but it looks for changes in any object and then recalculates the whole array. I've managed to set this up by using a combination of computed and watch functions. However they watch the whole array for changes and then recalculate the outcome-value for all objects in the array.
How can I watch for changes and then recalculate only the changed object?
Below is my current functions for recalculating the whole array (watching another property), but what I'm looking for could be completely different.
computed:
myArrayWasChanged() {
return [this.myArray.reduce((a, {vendors}) => a + vendors, 0), this.myArray.filter(item => item.discounted == false).length]
watch:
myArrayWasChanged: {
handler: function (val, oldVal) {
this.recalculateIsVendor();
Given the outcome is completely dependent on the other properties, it isn't really part of the component's state. Thus, in the component's data you could store the array without the outcome, and then calculate a new version of the array with the outcome as a computed property.
data: function () {
return {
myArrayWithoutOutcome: [
{
name: "First",
price: 10,
rebate: 5,
listPrice: 15
},
{
name: "Second",
price: 11,
rebate: 5,
listPrice: 16
}]
}
},
computed: {
myArrayWithOutcome: function () {
return this.myArrayWithoutOutcome.map(x => {
return {...x, outcome: this.calculateOutcome(x)}
})
}
},
methods: {
calculateOutcome(item) {
// Logic to calculate outcome from item goes here
return 0
}
}

transform json object to an array field

I want to transform a list of objects with object having this form
{
"idActivite": 1,
"nomActivite": "Accueil des participants autour d’un café viennoiseries",
"descriptionActivite": "",
"lieuActivite": "",
"typeActivite": "",
"horaireDebActivite": 1512028800,
"horaireFinActivite": 1512059388,
"horaireDebSession": 1512030600,
"horaireFinSession": 1512318588,
"nomSession": "",
"isInSession": false
}
to a one like this :
[
"idActivite": 1,
"nomActivite": "Accueil des participants autour d’un café viennoiseries",
"descriptionActivite": "",
"lieuActivite": "",
"typeActivite": "",
"horaireDebActivite": 1512028800,
"horaireFinActivite": 1512059388,
"horaireDebSession": 1512030600,
"horaireFinSession": 1512318588,
"nomSession": "",
"isInSession": false
]
using type script 2.5
Both are theoretically still objects and that isnt the right way to go about it! An array is simply a list of elements with a number index, the example you are giving uses a string to index and thus is still according to the JSON spec an object. If the issue you are having is to iterate through it use this:
for(var key in array){
console.log(array[key]);
}
Assuming you want an array like [ {key, value} ]
let x = { a: 1, b: 2 }
let y = []
// Note the 'in' keyword instead of 'of'
for (const key in x) {
y.push({ key: key, value: x[key] })
}
// Will print [ { key: 'a', value: 1 }, { key: 'b', value: 2 } ]
console.log(y)
Note that this solution scales linearly with the size of the array.

AngularJS filter by id returns multiple entrys

i had an array like this:
arr = [
{ID: 502, Description: 'aaa', code: 1122},
{ID: 2, Description: 'bbb', code: 2211},
{ID: 700, Description: 'ccc', code: 2222}
];
when i try to filter the ID I get all occurences of the specific number:
$(filter)('filter')( arr, { ID: 2 } )[0]
returns entry one ID: 502 but it should return the entry with ID: 2
Where is my fault?
According to the docs when used with an object it will match the element if it contains the value.
A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1".
There is a second option comparator passing true will cause it to perform a strict equality meaning it should only return exact matches.
$filter('filter')( arr, { ID: 2 }, true);
Fiddle: https://jsfiddle.net/enxbpjg0/
You could use a function instead of the object. So...
$filter('filter')(arr, function(value) {
return value.ID === 2;
});

Order array by value in NodeJS

I am learning node and now I'm trying to order an array like this:
"lng" : [{
"ES" : 5,
"EN" : 3,
"IT" : 4
}]
(This is a part of a query result in MongoDB), I need to order the array by the number:
"ES" : 5,
"IT" : 4,
"EN" : 3
I used sort() but this function orders the array alphabetically by the first parameter, but I need order by the second, I've tried a lot of things but without result.
Thank you for your help!
JavaScript has no ordered objects, so first you should transform your object to an array of this kind:
[
{ key: "ES", value: 5 },
{ key: "EN", value: 3 },
{ key: "IT", value: 4 }
]
And then sort by the value key.
You can easily do it as follows:
// ("mongoDbResult" is the variable with an object you get from MongoDB)
var result = mongoDbResult.lng;
result = Object.keys(result).map(function (key) {
return { key: key, value: result[key] };
});
And then just sort by the value key:
result.sort(function (a, b) {
return (a.value < b.value) ? -1 : 1;
});
As a result, you should get a sorted array in the result variable.
Thank you Nikita, adding the key and value the sort works perfectly, my problem now is make the query to get the results with specific key and value...
I can get the elements by the KEY:
db.users.find({"lng.key" : "ES"})
Or by the VALUE:
db.users.find({"lng.value" : 5})
But not the both at the same query :/
[EDIT]
I have find the solution, $elemMatch:
db.users.find({lng_array : {$elemMatch:{key:"ES", value:5}}})

Resources