Turn method ES6 find() to something in ES5 - javascript

I need to join values of 2 arrays of objects and make a third one out of it. I use es6 method find() to make it but i've been asked some es5 code for this piece of logic. I wanted to use indexOf() but i dont know how to make it unfortunately...
thanks for your very kind help.
const caByEmployee = [{
id: 8,
period1: 652.40,
period2: 3831.73,
name: 'Tam'
},
{
id: 18,
period1: 421.95,
period2: 1036.18,
name: 'Nathalie'
},
{
id: 20,
period1: 300.5,
period2: 1179.15,
name: 'Liliane'
}
]
const attendanceByEmployee = [{
id : 1,
period1 : 0,
period2 : 86
},
{
id : 8,
period1 : 98,
period2 : 520
},
{
id : 18,
period1 : 70,
period2 : 49
},
{
id : 20,
period1 : 4,
period2 : 227
}
]
const averageCartByEmployee = caByEmployee.map(function (ca) {
var attendance = attendanceByEmployee.find(function (attendance) {
return attendance.id === ca.id;
});
return {
id : ca.id,
name : ca.name,
period1: ca.period1 / attendance.period1 || 0,
period2: ca.period2 / attendance.period2 || 0
};
});
this give a result like so which is totally fine but not made with es5
[ { id: 8, 
name: 'Tam', 
period1: 6.657142857142857, 
period2: 7.368711538461539 }, 
{ id: 18, 
name: 'Nathalie', 
period1: 6.027857142857143, 
period2: 21.1465306122449 }, 
{ id: 20, 
name: 'Liliane', 
period1: 75.125, 
period2: 5.194493392070485 } ] 

Polyfilling find is trivial, see the link for one such polyfill but there are others out there.
You can't use indexOf because it looks for the thing actually in the array, and you want to match by id. (You could use findIndex, but it's also not an ES5 method.)
If you don't want to polyfill, you'll want a simple for loop, breaking when you find an entry with the matching id.

Related

Convert array to an array object with some modifications

i'm pretty beginner in the JavaScript and I really need help to convert an array to an array object. There are many examples here in stackOverflow, but I need some modidfication during this process, which is why I couldn't do anything
For example I have:
data = [{id: 21, name: "jack"} , {id: 185, name: "yas"}]
and I need to convert it with something like that (id key change to student_id, and present = true, should be added), and the length of this array is dynamic and will change over time.
[
{
"student_id" : 21,
"present" = true
},
{
"student_id" : 185,
"present" = true
}
]
I need to add these array object to:
const data: any = {
here....
};
your help will be much appreciated.
Assuming your data actually looks more like this
data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}]
This is a simple matter of mapping the array to a new format with the properties you want
const data = [{id: 21, name: "jack"}, {id: 185, name: "yas"}]
const newData = data.map(({ id }) => ({
student_id: id,
present: true
}))
console.log(newData)

Find element that doesn't have a specific key property in JS objects array

i have an array :
[
0 {
Id : 01
country : "Algery"
name: "Amnesty"
},
1 {
Id : 02
country : "USA"
name: "Alarmy"
},
2 {
Id : 03
country : "Alaska"
}
]
And i want to find in this list the object that has not the property "Name".
I tried by doing myArray.find((pers) => !(pers.name));
But it doesn't work.. anyone have an idea here?
You can do:
const arr = [{ Id: 01, country: "Algery", name: "Amnesty" }, { Id:02, country: "USA", name: "Alarmy" }, { Id: 03, country:"Alaska" }];
console.log(arr.find(obj => !('name' in obj)));
The code is working fine only for falsy name. To check if a property exists, you could take the in operator.
const
array = [{ Id: 01, country: "Algery", name: "Amnesty" }, { Id: 02, country: "USA", name: "Alarmy" }, { Id: 03, country: "Alaska" }];
console.log(array.find(person => !('name' in person)));
This approach returns only the first found item. For getting all items, you could apply Array#filter for getting an array.
Beside above mention ways, one more way to achieve this is by using hasOwnProperty method
For your reference :
for ( var key in jsonArray) {
if (!jsonArray[key].hasOwnProperty("name")) {
console.log(jsonArray[key]);
}
}

How does this code work in context with reduce function?

It might be a very basic question for people here but I have to ask away.
So I was going through reducce recently and I came through this example where I could find the maximum of some value in an array of object. Please, have a look at this code.
var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14
}, {
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30
}, {
id: 41,
name: "Tallissan Lintra",
years: 16
}, {
id: 99,
name: "Ello Asty",
years: 22
}
];
If I write soemthing like this to find the maximum years,
var oldest_of_them_all = pilots.reduce(function (old, current) {
var old = (old.years > current.years) ? old.years : current.years;
return old
})
I get 22 as my value, and if I dont involve the property years, i.e-
var oldest_of_them_all = pilots.reduce(function (old, current) {
var old = (old.years > current.years) ? old : current;
return old
})
I get the object Object {id: 2, name: "Temmin 'Snap' Wexley", years: 30} as my value. Can someone explain why the first example is wrong and what is happening in there? Also, if I Just want to fetch the years value, how can I do that? Thanks in advance.
In the first example, as you are not returning the object there is no object property (years) of the accumulator (old) after the first iteration. Hence there is no year property to compare with.
var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14
}, {
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30
}, {
id: 41,
name: "Tallissan Lintra",
years: 16
}, {
id: 99,
name: "Ello Asty",
years: 22
}
];
var oldest_of_them_all = pilots.reduce(function (old, current) {
console.log(old);// the value is not the object having the property years after the first iteration
var old = (old.years > current.years) ? old.years : current.years;
return old;
})
console.log(oldest_of_them_all);

Find and update value in array of nested objects

I have an object array as follows:
products = [
{
id: 1,
title: "Product 1",
specifications: {
price: 1.55,
discount: 15,
attributes: [
{
l1: 100,
l2: 80
height:200,
weight: 15,
parameters: [
{
id: 199199 // this is how I identify the parameter
size: 185 // this is what I want to change
}, ...
]
}, ...
]
}
}, ...
]
... and an array of changes to parameters I want to apply, for example: change size to 189 where product.specifications.attributes.parameters.id == 199199.
I'd like to do this without flattening any elements as they are part of a Vue.js data structure, it will break the reactivity.
How could I do this? I am open to using Underscore or lo-dash
This looks ugly, but it is effective:
To make it more dynamic, let's use variables: identifier will be your '199199' value and new_size for the '189' value.
methods: {
updateRecord: function(identifier, new_size) {
this.products.map(function(product) {
product.specifications.attributes.map(function(attribute) {
attribute.parameters.map(function(parameter) {
if (parameter.id == identifier) parameter.size = new_size;
})
});
});
}
}
Here is a working fiddle: https://jsfiddle.net/crabbly/eL7et9e8/
_.forEach(products, function(product) {
_.forEach(_.get(product, 'specifications.attributes', []), function(attribute) {
_.set(_.find(attribute.parameters, {id: 199199}), 'size', 189);
});
});
I believe what you want is underscore's findIndex() - http://underscorejs.org/#findIndex. Once you find which element in the array you want to apply the changes to (comparing the nested id to what you are looking for) you can then make the change to that particular element.

Looking for a way to sort an array of objects in javascript

so I have a JSON array that looks like this:
[
{
row: [
{
boat: {
description: 'Books',
version: '2',
id: 6
},
airplanes: [
{
airplane: [
{
description: 'DVD',
version: 2,
uid: 69,
wid: 65,
id: 84
}
],
trains: {
train: [
{
description: 'Pictures',
version: 2,
id: 149
}
],
actions: [
{
description: 'This is a really long sentence.',
version: 2,
tid: 69.01,
id: 452
},
{
description: 'article 2',
version: 2,
tid: 69.02,
id: 453
},
{
description: 'developer 1',
version: 2,
tid: 69.03,
id: 454
}
]
}
},
{
airplane: [
{
description: 'Games',
version: 2,
uid: 65,
wid: 61,
id: 80
}
],
trains: {
train: [
{
description: 'another great descriptions.',
version: 2,
id: 145
}
],
actions: [
{
description: 'being indecisive is good.',
version: 2,
tid: 65.01,
id: 442
},
{
description: 'couches are comfortable',
version: 2,
tid: 65.02,
id: 443
}
]
}
}
]
}
]
}
]
I am trying to sort the above output by 'wid' in ascending order but still be able to preserve the overall order. For example in the above the wid in element 0 of the array is 65, and element 1 of the array the wid value is 61. Therefore, element 1 and element 0 should be swapped. Is there any built in javascript method to sort json like this?
I will have a json array output a lot larger than the provided example.
Both Underscore and LoDash have a sort method that will do what you're looking for. In this example I am assuming that you have the data structure you showed stored in a variable called data.
_.each(data, function(obj) {
_.each(obj.row, function(row) {
// note the reassignment, _.sortBy does not sort in-place
row.airplanes = _.sortBy(row.airplanes, function(airplane) {
return airplane.wid; // This will sort ascending.
// To sort descending, simply multiply by -1
});
});
});
So what is this doing? It's taking each array element in your root data structure and looping over it (that's the first _.each). Then in each of those objects, it is looping over each row element and sorting row.airplanes array by the wid element contained in each.
Hopefully this helps you. As an aside, that data you posted is strictly invalid JSON. Each key should be double quoted, i.e., "row", instead of just row and single quotes are invalid for delimiting strings, i.e., "DVD" instead of 'DVD'. Also, your boat version is a string whereas your other version identifiers are integers, it's a good idea to try and keep your version identifiers as integers.
I recommend using the excellent jq commandline JSON processor. Extremely fast since it was written in portable C. Easy to understand documentation.
cat <file.json> | jq . -S

Categories