can anybody explain me the work of the .map() method here - javascript

explain the use of the arrow function inside the .map() method here.
let mFunc= function(fname, data) {
for (i in data.shop) { //iterating through the JSON data
if (data.shop[i].name == fname) {
let dataSv = data.shop[i];
// We found a match, display details
for (y in dataSv){
if (typeof dataSv[y][0] === 'object') {
dataSv[y] = dataSv[y].map(z => z.name) // explain me this part
}
alert(i + " : " + dataSv[y])
}
}
}
}
}

.map(z => z.name)
Is shorthand for:
.map(z => {
return z.name;
})
So when you are only going to write a single line inside your function, and that is a return statement, you can use this shorthand.

This is just converting array of objects to array of strings which will contain the name of each element.
If you write an expression after => in array function with it will return that expression.
Body of arrow function
Arrow functions can have either a concise body or the usual block body.
In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement
dataSv[y] = dataSv[y].map(z => z.name)
Is equivalent to
dataSv[y] = dataSv[y].map(z => {
return z.name;
})

Check this example. It may make it clearer
dataSv = [
[
{name: 'one', id: 1},
{name: 'two', id: 2},
{name: 'three', id: 3}
],
[
{name: 'eleven', id: 11},
{name: 'twelve', id: 12},
{name: 'thirteen', id: 13}
],
[
{name: 'twenty-one', id: 21},
{name: 'twenty-two', id: 22},
{name: 'twenty-three', id: 23}
]
]
dataSv[0] = dataSv[0].map(z => z.name)
dataSv[1] = dataSv[1].map(z => z.name)
dataSv[2] = dataSv[2].map(z => z.name)
console.info(dataSv)

It will return simply the "name" property of each element of the array, instead of the original object.
Basically whatever the code on the right-hand side of the => evaluates to becomes the returned value for each array element that .map() iterates over.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map for more info and a runnable demo you can play with

Related

Replacing an one of the objects in an array of objects in javaScript

I have below array and object and I am trying to replace the entire object of the array where id matches.
this.integrationActionsArray = [{id: 1, key: 'some key', value: 'some value'}]
myObject = {id: 1, key: 'another key', value: 'another value'}
so far I have made below attempts to change the one of the entire objects of an array of objects
this.integrationActionsArray
.find(data => {
if (data.id == myId) {
data = myObject
}
})
console.log(this.integrationActionsArray)
Expectation of the above log is something like below
[{id: 1, key: 'another key', value: 'another value'}]
but it is still like
[{id: 1, key: 'some key', value: 'some value'}]
I have tried using forEach, filter, map and every other iterator but still no luck.
When you do data = myObject, what you are expecting does not happen.
data is just a local variable that points to the integrationActionsArray array element in the find callback method. Once you run the above statement, you are not changing anything in the array, instead just reassigning data.
A simple representation of what is happening above.
let data = { a : 1 , b : 2 };
let data1 = data;
data1={x : 1};
//You can not expect data to change
console.log(data);
To fix this grab the index, and then replace the element in the array.
const integrationActionsArray = [{id: 1, key: 'some key', value: 'some value'}];
const myObject = {id: 1, key: 'another key', value: 'another value'};
const myId = 1;
integrationActionsArray
.forEach((data,index) => {
if (data.id == myId) {
integrationActionsArray[index] = myObject
}
})
console.log(integrationActionsArray)
Note: The above code will work with find() but find returns a specific element. And a simple forEach is ideal for the above case.

How do I get an object parameter by its id?

I need to detect an object in an array with its Id.
My first array looks like that:
{ [id: 9, name: 'abc'], [id: 2, name 'def'], [id: 40, name: 'gh'] } (Id & name),
while that other array is:
{ [class: 'physics', Tid: 9], [class: 'computer science', Tid: 9], [class: 'Biology', Tid: 40] }.
I need to match the parameter "name" from the first array by its ID to its "class" (for example, "physics" relates to Tid=9 which is "abc" and "Biology" relates to Tid=40 which is "gh").
How can I elegantly do so without changing the way the data comes? (It comes from a database with ASP.NET web service in JSON)
You could use $http.get() which has success and error callback functions, which returns a promise object. Using this, you can setup a condition to map the id and get your desired result.
Something like this.
var myObject1 = {};
var myArray1 = [];
var myObject2 = {};
var myArray2 = [];
$http.get('json-file')
.success(function(data)) {
myObject1.myArray1 = data;
}
$http.get('json-file')
.success(function(data)) {
myObject2.myArray2 = data;
}
/* inside a loop if required */
if (myObject1.myArray1[index].id == myObject2.myArray2[index].Tid) {
/* perform logic */
}
This code would be present inside a service or a controller.
Haven't tested it so unsure of the syntax but promise objects are the way to go.
Hope this helps.
This returns an array of arrays. Each array in the array contains two objects matched by id === Tid. As far as I can tell that's what you want.
(Note that I think you provided broken sample arrays, I adjusted and scrambled the numbers around so you could see it work more clearly).
var arr1 = [ {id: 9, name: 'abc'}, {id: 2, name: 'def'}, {id: 40, name: 'gh'} ];
var arr2 = [ {class: 'physics', Tid: 2}, {class: 'computer science', Tid: 40}, {class: 'Biology', Tid: 9} ];
var arrFinal = arr1.map ( function ( d ) {
var matched = arr2.find ( function ( obj ) {
return obj.Tid === d.id;
} );
return [ d, matched ];
} );
If you iterate arrFinal you'll see it contains the matched objects.

Js/Lodash get parent object of array value

Given the following array:
var arr = [ { id: '123', numbers: [123,456,789] }, { id: '456', numbers: [6543,344,34534] }]
How can I get the parent object of the object containing 123 in the numbers array.
Eg. I want to search '123' and get:
{ id: '123', numbers: [123,456,789] }
I've tried using:
https://lodash.com/docs#find
_.find(arr, 123);
_.findKey(arr,123);
Can this be done with _map?
https://lodash.com/docs#map
Since you are already using lodash, you can use collection.find.
Syntax:
_.find(collection, [predicate=_.identity], [fromIndex=0])
[predicate=_.identity] is a function that is executed for every iteration. So instead of passing 123, pass this function.
Note: This can be done using Array functions, but they have compatibility issues and since you are already using lodash, in my understanding, this approach would suit better.
var arr = [{
id: '123',
numbers: [123, 456, 789]
}, {
id: '456',
numbers: [6543, 344, 34534]
}]
// ES6 version
var r = _.find(arr, x => x.id == '123');
// ES5 version
var r1 = _.find(arr, function(el){ return el.id == '123' });
console.log(r, r1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>
#gcampbell is correct.
Translate to JavaScript, it should be
_.find(arr, function(x) {
return x.numbers.includes(123);
});
You can refer to the Underscore documentation for further information.

How does Ember map function expect parameters?

I want to understand how the below code works in EmberJS?
Ember.$.map($this.get('myMap'), function(entitlements, id) {
// What is entitlements & id here & what should be $this.get('myMap')?
})
is this conventional/standard JS syntax ?
Any examples would be great ?
Ember.$ with lead you to jQuery, so you're using jQuery's map method.
Essentially what it does it call a function for each element in the array, allowing you to "map" that value to another and return it to be added to a new array. For instance:
If you have an array of javascript objects like var names = [{ name: 'John', age: 12}, {name: 'Fred', age: 14}] and you wanted to extract all names to a new array you could do:
var names = [{ name: 'John', age: 12}, {name: 'Fred', age: 14}];
var result = Ember.$.map(names, function(instance, index) {
return instance.name
})
console.log(result) //Would print ['John', 'Fred'];
You could do all sort of things like return new objects to be added to the array.

Given an array of objects, find the object with a particular key

Given an array of objects, what is the best way to find the object with a particular key in JS?
Using jQuery and underscoreJS is fine. I'm just looking for the easiest / least code answer.
Example:
An array of objects, where each object has a "name". Find the object with a particular "name".
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
My current solution:
Pass in the array, the key (e.g. "name"), and the value (e.g. "C").
function getObject(myArray, searchKey, searchValue) {
myArray.forEach(function(element){
if (element[searchKey] == searchValue) {
return element;
}
});
}
You can use Underscore.js's _.where function, like this
console.log(_.where(people, {
"name": "C"
}));
# [ { name: 'C' } ]
This returns all the objects in the array, which exactly matches the object we pass as the second argument.
You should go with grep of jQuery
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
var obj1= jQuery.grep(people,function(n,i){return (n.name=='A')})
Using _.filter:
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
var filteredPeople = _.filter(people, function(obj){
return obj['name'] == 'C';
});
console.log(JSON.stringify(filteredPeople)) // [{"name":"C"}]
If you want an array without the matched object(s), use _.reject:
var filteredPeople = _.reject(people, function(obj){
return obj['name'] == 'C';
});
console.log(JSON.stringify(filteredPeople)) // [{name: "A"}, {name: "B"}]
Without any custom library you can also do this. Please take a look at the following code
var people = [{name: "A"}, {name: "B"}, {name: "C"}],
match=function(element){
return element.name==="A";
};
console.log(people.filter(match));
But it is kind of static code . I don't know how to pass the key and value to the match() function.
I'm surprised not to find the obvious answer here, so: To do that with Underscore, you'd use _.find:
function getObject(myArray, searchKey, searchValue) {
return _.find(myArray, function(entry) { return entry[seachKey] === searchValue; });
}
You don't need Underscore for this, though; JavaScript's array type has find (as of ES5):
function getObject(myArray, searchKey, searchValue) {
return myArray.find(function(entry) { return entry[searchKey] === searchValue; });
}
As of ES2015+, you can make it more concise with an arrow function and destructuring:
function getObject(myArray, searchKey, searchValue) {
return myArray.find(({[searchKey]: value}) => value === searchValue);
}
Live example of that last one:
function getObject(myArray, searchKey, searchValue) {
return myArray.find(({[searchKey]: value}) => value === searchValue);
}
const people = [{name: "A"}, {name: "B"}, {name: "C"}];
console.log(getObject(people, "name", "C"));

Categories