How can I find particular value from array in react native - javascript

I am trying to find each link value in different variables according to their name , like if name if facebook then facebooklink should filter , same lite twitter and all . But don't want to give index number . sometime fabook should be o index sometime twitter will be on 0 index . Please help
socialMediaDetails:
socialMediaDetail: Array(2)
0:
link: "HARIRAM#twitter.com"
name: "twitter"
__typename: "SocialMediaDetail"
__proto__: Object
1:
link: "VarnaHERO#facebook.com"
name: "facebook"
__typename: "SocialMediaDetail"
__proto__: Object
2:
link: "linkedIn#linkedin.com"
name: "linkedIn"
__typename: "SocialMediaDetail"
const socialMediaData=socialMediaDetails.socialMediaDetail;
const Steplabels = socialMediaData.filter((item) => {
return item.name === "twitter"
});
Thanks

You can use find method, like this:
requiredMediaByName = (name) => {
return state.socialMediaDetails.socialMediaDetail.find(data => data.name === name);
};
console.log(requiredMediaByName('facebook'));
Note that find returns the first matching element in the array and it won't check the other elements if you get it on fist match. If you want all the elements to be returned then you should use for loop and get all of them.

There are a few ways this can be achieved - the simplest way would be to use a for .. of loop if you're just looking for the first item matching on name:
function findLinkByName(name) {
for (const item of state.socialMediaDetails.socialMediaDetail) {
if (item.name === name) {
return item.link;
}
}
}
For other cases such as returning a subset of items where multiple matches on name exist, then a simple solution based on filter() and map() could be achieved like this:
function findLinksByName(name) {
return state.socialMediaDetails.socialMediaDetail
.filter(item => item.name === name)
.map(item => item.link);
}
Here's a snippet showing both in action:
var state = {
socialMediaDetails: {
socialMediaDetail: [{
link: "HARIRAM#twitter.com",
name: "twitter"
}, {
link: "VarnaHERO#facebook.com",
name: "facebook"
}, {
link: "linkedIn#linkedin.com",
name: "linkedIn"
}, {
link: "another twitter link",
name: "twitter"
}
]
}
}
/*
Find link of first item matching by name (or undefined if no match found)
*/
function findLinkByName(name) {
for (const item of state.socialMediaDetails.socialMediaDetail) {
if (item.name === name) {
return item.link;
}
}
}
/*
Find links for all items with matching name (or empty array if no
matches found)
*/
function findLinksByName(name) {
return state.socialMediaDetails.socialMediaDetail
.filter(item => item.name === name)
.map(item => item.link);
}
console.log(findLinkByName('twitter'));
console.log(findLinkByName('facebook'));
console.log(findLinksByName('twitter'));
console.log(findLinksByName('facebook'));
Hope that helps!

You could use:
if you only want to know if the value exists or not
var doesExist = arr.some(function(ele) {
return ele.id === '21';
});
If you want to get the value you are searching for:
var data = arr.find(function(ele) {
return ele.id === '21';
});
if (data) {
console.log('found');
console.log(data); // This is entire object i.e. item not boolean
}
I have used following array for this example:
var arr = [];
var item1 = {
id: 21,
label: 'Banana',
};
var item2 = {
id: 22,
label: 'Apple',
};
arr.push(item1, item2);

Related

How to determine if Javascript array contains an object with an attribute that is equal to each other

I have an array like
selectedData = [{
Name = 'Michelle',
LRN = '100011'
},
{
Name = 'Micheal',
LRN = '100011'
},
{
Name = 'Mick',
LRN = '100012'
} // so on....
]
I am sending this array through a function and that simply checks if the LRN attribute of each object is same if not it throws error. I have written the function as -
createSet(selectedData) {
this.selectedData.forEach (element => {
//the condition
}
else
{
this.openSnackBar ("LRN mismatching");
}
}
How do I check if the LRN attribute of each object is same? I don't want loop unless I have to. I'm working with more than thousand records. I appreciate all the help. :)
You could take Array#every and check the first item to each other. The method stops the iteration if the condition is false and returns then false, if not then true.
The callback's parameter can have three parts, one for the item, the next for the index and the third one has the reference to the array.
In this case only the item is used with a destructuring of LRN and the array. The unneeded index is denoted by an underscore, which is a valid variable name in Javascript.
if (!array.every(({ LRN }, _, a) => LRN === a[0].LRN)) {
this.openSnackBar ("LRN mismatching");
}
Code with example of all property LRN having the same value.
const
selectedData = [{ Name: 'Michelle', LRN: '100011' }, { Name: 'Micheal', LRN: '100011'}, { Name: 'Mick', LRN: '100011' }];
if (!selectedData.every(({ LRN }, _, a) => LRN === a[0].LRN)) {
console.log("LRN mismatching");
} else {
// just to show
console.log('OK');
}
Mismatching
const
selectedData = [{ Name: 'Michelle', LRN: '100011' }, { Name: 'Micheal', LRN: '100011'}, { Name: 'Mick', LRN: '100012' }];
if (!selectedData.every(({ LRN }, _, a) => LRN === a[0].LRN)) {
console.log("LRN mismatching");
} else {
// just to show
console.log('OK');
}
An easy beginner-friendly solution would be:
function allLRNMatch(data) {
if (data.length < 2) {
return true;
}
const firstLRN = data[0].LRN;
for (const element of data) {
if (element.LRN !== firstLRN) {
return false;
}
}
return true;
}
You iterate through the array and check each element's LRN attribute with the first one. As soon you find a non-matching one, you can immediately return.
For a more functional approach, you could also use Array.prototype.some instead of the for loop to achieve this.
Sorry but there's no other way, you will need to loop through them to compare the value, once it's an array of objects, it would be different if it was a LRN array.
On this case I would use it this way:
const sameLrnArrPosition = [];
checkLrn(arr, valueToBeCompared) {
arr.forEach((element, index)=>{
if(element.lnr === valueToBeCompared){
sameLrnArrPosition.push(*here you can get the element or the index*);
}
})
}
This way you can have the objects that have the same value or the index, to acces them on the array and change a value or something.

i wanna return correctly children's object. how can i?

function Ha8(arr, id) {
let result = [];
for(let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i].children)) {
// if it is a array, it going to be run recursive
result.push(arr[i].children)
const col = Ha8(result[i], id);
if(col === id) {
// find it in array in array
return result
// then return the id object,
} else {
continue; // still can't find.. go ahead!
}
} else if (arr[i]['id']===id) {
return arr[i] // will return valid id object
}
return null // if its none , return null, or parameter id is undefined.
}
}
I m write Intended direction. but its not work..
how can i fix ? give me some tip please.
let input = [
{
id: 1,
name: 'johnny',
},
{
id: 2,
name: 'ingi',
children: [
{
id: 3,
name: 'johnson',
},
{
id: 5,
name: 'steve',
children: [
{
id: 6,
name: 'lisa',
},
],
},
{
id: 11,
},
],
},
{
id: '13',
},
];
output = Ha8(input, 5);
console.log(output); // --> { id: 5, name: 'steve', children: [{ id: 6, name: 'lisa' }] }
output = Ha8(input, 99);
console.log(output); // --> null
I wanna return like that, but only return 'null' ..
need to check children's id and return children's object by using recursive.
so i write like that. but i have no idea..
how to return correctly children id's element?
I will give you an answer using a totally different approach, and using the magic of the JSON.stringify() method, more specifically the replacer optional parameter, which allows the use of a callback function that can be used as a filter.
As you can see, it simplifies a lot the final code. It could also be modified to introduce not only an id, but also any key or value, as I did in my final approach.
EDIT: Following your suggestion, as you prefer your function to be recursive, I recommend you to use the Array.reduce() method. It allows an elegant iteration through all the properties until the needs are met.
Using null as initial value, which is the last argument of the reduce method, it allows to iterate through all fields in the array in the following way:
The first if will always be skipped on the first iteration, as the initial value is null.
The second if will set the currentValue to the accumulator if the property id exists and is equal to the value you are trying to find
The third if, which you could add an Array.isArray() to add a type validation, will check if the property children exists. As it is the last one, it will only work if all the other conditions aren't met. If this property exists, it will call again Ha8Recursive in order to start again the process.
Finally, if neither of this works, it should return null. The absence of this last condition would return undefined if the input id doesn't exist
const Ha8 = (array, inputKey, inputValue) => {
let children = null;
JSON.stringify(array, (key, value) => {
if (value[inputKey] && value[inputKey] === inputValue) {
children = value;
}
return value;
});
return children;
};
const Ha8Recursive = (array, inputKey, inputValue) => {
return array.reduce((accumulator, currentValue) => {
if (accumulator) {
return accumulator;
} else if (currentValue[inputKey] && currentValue[inputKey] === inputValue) {
return currentValue;
} else if (currentValue.children) {
return Ha8Recursive(currentValue.children, inputKey, inputValue);
} else {
return null;
}
}, null)
}
const input = [{"id":1,"name":"johnny"},{"id":2,"name":"ingi","children":[{"id":3,"name":"johnson"},{"id":5,"name":"steve","children":[{"id":6,"name":"lisa"}]},{"id":11}]},{"id":"13"}];
console.log('JSON stringify function');
console.log(Ha8(input, 'id', 5));
console.log('Recursive function')
console.log(Ha8Recursive(input, 'id', 5));

JavaScript - Filter object based on multiple values

I need to filter some data based on multiple values. Language, title and slug
[
{
de: "4567uy55",
en: "654321",
lang: [
{
id: "654321",
language: "English",
title: "Title1"
},
{
id: "4567uy55",
language: "German",
title: "Title2"
}
],
slug: 'some-slug'
},
...
]
What I have now returns all objects which have one or part of the filters(in case title is This is a title, the word this should match), but I need to return objects which have all of them.
I used an object flattner just to get all properties and values in one object, but I can't get it to filter the way I need it.
multiFilter = (arr, filters) => {
console.log(filters)
console.log(arr)
let newArray = []
for (let c of arr) {
let flatCourse = flatten(c)
for (let k in flatCourse) {
const keyArr = k.split('/')
const filterKeys = Object.keys(filters)
Object.keys(filters).map((key) => {
if (keyArr.includes(key)) {
const flatVal = flatCourse[k].toString().toLowerCase()
const filterVal = filters[key].toString().toLowerCase()
console.log(flatVal)
console.log(filterVal)
if (flatVal.includes(filterVal)) {
arr = []
arr.push(c)
newArray.push(c)
}
}
})
}
}
return newArray
}
Filters look like this:
[
language:["English"],
title: ["Some title"],
slug:["some slug"]
]
Instead of mixing for loops and functional chaining you could just go with one of them:
multiFilter = (arr, filters) =>
arr.map(flatten).filter(el => // filter out elements from arr
Object.entries(filters).every(([fKey, fValues]) => // ensure that every key is included in the object
Object.entries(el).some(([oKey, oValue]) =>
oKey.split("/").includes(fKey) && fValues.includes(oValue)// make sure that at least one of the values equals the elements value
)
)
);
arr.filter(course => {
// Returns an array of booleans corresponding to whether or not each filter condition is satisfied
return Object.keys(filters).map(key => {
return filters[key].map(filter => {
// Special case here because lang is an array
if (key == 'language' && course.lang != undefined) {
return course.lang.some(lang => lang[key].includes(filter))
}
if (course[key] == undefined) {
return false
}
return course[key].includes(filter)
}).every(result => result == true)
}).every(result => result == true)
})

Group the same `category` objects [duplicate]

This question already has answers here:
Group array items using object
(19 answers)
Closed 6 years ago.
I'm trying to group the raw data from:
items:
[
{
category: "blog",
id : "586ba9f3a36b129f1336ed38",
content : "foo, bar!"
},
{
category: "blog",
id : "586ba9f3a36b129f1336ed3c",
content : "hello, world!"
},
{
category: "music",
id : "586ba9a6dfjb129f1332ldab",
content : "wow, shamwow!"
},
]
to
[
{
category: "blog",
items:
[
{
id : "586ba9f3a36b129f1336ed38",
content : "foo, bar!"
},
{
id : "586ba9f3a36b129f1336ed3c",
content : "hello, world!"
},
]
},
{
category: "music",
items:
[
{
id : "586ba9a6dfjb129f1332ldab",
content : "wow, shamwow!"
}
]
}
]
The format like this helps me to print the same category data together in the frontend.
The content of the category field is dynamically, so I'm not sure how do I store it to a temporary object and sort them, any thoughts?
(I can't think a better title for the question, please edit if you got a better title.)
You can do it using Array#reduce in one pass:
var items = [{"category":"blog","id":"586ba9f3a36b129f1336ed38","content":"foo, bar!"},{"category":"blog","id":"586ba9f3a36b129f1336ed3c","content":"hello, world!"},{"category":"music","id":"586ba9a6dfjb129f1332ldab","content":"wow, shamwow!"}];
var result = items.reduce(function(r, item) {
var current = r.hash[item.category];
if(!current) {
current = r.hash[item.category] = {
category: item.category,
items: []
};
r.arr.push(current);
}
current.items.push({
id: item.id,
content: item.content
});
return r;
}, { hash: {}, arr: [] }).arr;
console.log(result);
Or the ES6 way using Map:
const items = [{"category":"blog","id":"586ba9f3a36b129f1336ed38","content":"foo, bar!"},{"category":"blog","id":"586ba9f3a36b129f1336ed3c","content":"hello, world!"},{"category":"music","id":"586ba9a6dfjb129f1332ldab","content":"wow, shamwow!"}];
const result = [...items.reduce((r, { category, id, content }) => {
r.has(category) || r.set(category, {
category,
items: []
});
r.get(category).items.push({ id, content });
return r;
}, new Map).values()];
console.log(result);
Personally, without any helper libraries, I'd just do this
var step1 = items.reduce((result, {category, id, content}) => {
result[category] = result[category] || [];
result[category].push({id, content});
return result;
}, {});
var result = Object.keys(step1).map(category => ({category, items: step1[category]}));
Which babel converts to
var step1 = items.reduce(function (result, _ref) {
var category = _ref.category,
id = _ref.id,
content = _ref.content;
result[category] = result[category] || [];
result[category].push({ id: id, content: content });
return result;
}, {});
var result = Object.keys(step1).map(function (category) {
return { category: category, items: step1[category] };
});
So I just solved the question with the following code (jsfiddle):
// Items
// var items = []
// Create an empty object, used to store the different categories.
var temporaryObject = {}
// Scan for each of the objects in the `items` array.
items.forEach((item) =>
{
// Create a category in the teporary object if the category
// hasn't been created.
if(typeof temporaryObject[item.category] === "undefined")
temporaryObject[item.category] = []
// Push the item to the its category of the `temporaryObject`.
temporaryObject[item.category].push({
id : item.id,
content: item.content
})
})
// Create a empty array used to stores the sorted, grouped items.
var newItems = []
// Scan for each of the category in the `temporaryObject`
for(var category in temporaryObject)
{
// Push the new category in the `newItems` array.
newItems.push({
category: category,
items : []
})
// Get the last category index of the `newItems` array,
// so we can push the related data to the related category.
var lastItem = newItems.length - 1
// Scan for the related category in the `temporaryObject` object.
temporaryObject[category].forEach((item) =>
{
// Push the related data to the related category of the `newItems` array.
newItems[lastItem].items.push(item)
})
}
// Prints the sorted, grouped result.
console.log(newItems)

How to use lodash to find and return an object from Array?

My objects:
[
{
description: 'object1', id: 1
},
{
description: 'object2', id: 2
}
{
description: 'object3', id: 3
}
{
description: 'object4', id: 4
}
]
In my function below I'm passing in the description to find the matching ID:
function pluckSavedView(action, view) {
console.log('action: ', action);
console.log('pluckSavedView: ', view); // view = 'object1'
var savedViews = retrieveSavedViews();
console.log('savedViews: ', savedViews);
if (action === 'delete') {
var delete_id = _.result(_.find(savedViews, function(description) {
return description === view;
}), 'id');
console.log('delete_id: ', delete_id); // should be '1', but is undefined
}
}
I'm trying to use lodash's find method: https://lodash.com/docs#find
However my variable delete_id is coming out undefined.
Update for people checking this question out, Ramda is a nice library to do the same thing lodash does, but in a more functional programming way :)
http://ramdajs.com/0.21.0/docs/
lodash and ES5
var song = _.find(songs, {id:id});
lodash and ES6
let song = _.find(songs, {id});
docs at https://lodash.com/docs#find
The argument passed to the callback is one of the elements of the array. The elements of your array are objects of the form {description: ..., id: ...}.
var delete_id = _.result(_.find(savedViews, function(obj) {
return obj.description === view;
}), 'id');
Yet another alternative from the docs you linked to (lodash v3):
_.find(savedViews, 'description', view);
Lodash v4:
_.find(savedViews, ['description', view]);
You can do this easily in vanilla JS:
Using find:
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];
const view = 'object2';
const delete_id = savedViews.find(obj => {
return obj.description === view;
}).id;
console.log(delete_id);
Using filter (original answer):
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];
const view = 'object2';
const delete_id = savedViews.filter(function (el) {
return el.description === view;
})[0].id;
console.log(delete_id);
With the find method, your callback is going to be passed the value of each element, like:
{
description: 'object1', id: 1
}
Thus, you want code like:
_.find(savedViews, function(o) {
return o.description === view;
})
You don't need Lodash or Ramda or any other extra dependency.
Just use the ES6 find() function in a functional way:
savedViews.find(el => el.description === view)
Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:
bloat your bundled code size,
you will have to keep them up to date,
and they can introduce bugs or security risks
for this find the given Object in an Array, a basic usage example of _.find
const array =
[
{
description: 'object1', id: 1
},
{
description: 'object2', id: 2
},
{
description: 'object3', id: 3
},
{
description: 'object4', id: 4
}
];
this would work well
q = _.find(array, {id:'4'}); // delete id
console.log(q); // {description: 'object4', id: 4}
_.find will help with returning an element in an array, rather than it’s index. So if you have an array of objects and you want to find a single object in the array by a certain key value pare _.find is the right tools for the job.
Import lodash using
$ npm i --save lodash
var _ = require('lodash');
var objArrayList =
[
{ name: "user1"},
{ name: "user2"},
{ name: "user2"}
];
var Obj = _.find(objArrayList, { name: "user2" });
// Obj ==> { name: "user2"}
You can use the following
import { find } from 'lodash'
Then to return the entire object (not only its key or value) from the list with the following:
let match = find(savedViews, { 'ID': 'id to match'});
var delete_id = _(savedViews).where({ description : view }).get('0.id')
Fetch id basing on name
{
"roles": [
{
"id": 1,
"name": "admin",
},
{
"id": 3,
"name": "manager",
}
]
}
fetchIdBasingOnRole() {
const self = this;
if (this.employee.roles) {
var roleid = _.result(
_.find(this.getRoles, function(obj) {
return obj.name === self.employee.roles;
}),
"id"
);
}
return roleid;
},

Categories

Resources