How to get data by id from an object - javascript

I have an object Like
How to get single row by Id?

You can use Array#find function and pass a condition into it like
arr.find(item => item.id === 1)
Example
const users = [
{id: 1, name: 'A'},
{id: 2, name: 'B'},
];
const user = users.find(item => item.id === 1);
console.log(user);

Use find()
var item = yourArray.find(item => item.id === 2053);
DEMO
const yourArray = [
{Id: 2053, title: 'sass'},
{Id: 2054, title: 'sdss'},
];
const found = yourArray.find(item => item.Id ===2053);
console.log(found);

Yo can also use
var requiredItem = array.filter(i => i.id == 2054)
Example
var arrayNew = [
{id: 2053, name: 'sxsxs'},
{id: 2054, name: 'sss'}
];
var requiredItem = arrayNew.filter(i => i.id == 2054);
console.log(requiredItem);

let obj = [{
"id" : 1,
"Title" : "Hi"
},{
"id" : 11,
"Title" : "Hello"
}]
function filterById(ids) {
return obj.filter((obj) => {return obj.id == ids})
}
console.log(filterById(11))

Related

Compare one array with a nested array and push value into a new array with same index in Javascript

I have 2 arrays
const arrayOne = [
{id: '110'},
{id: '202'},
{id: '259'}
];
const arrayTwo = [
{data: [{value: 'Alpha', id: '001'}]},
{data: [{value: 'Bravo', id: '202'}]},
{data: [{value: 'Charlie', id: '110'}]},
{data: [{value: 'Delta', id: '202'}]}
];
I need to create a new array comparing arrayOne[idx].id with arrayTwo[idx].data[idx2].id
Upon match, I need to create an array pushing value (arrayTwo[idx].data[idx2].value) to the new array against each index in arrayOne.
In this example, I would get newArray = [null, 'Bravo', null, Delta]
What I have tried:
arrayOne.map(item => ({
...item,
result: arrayTwo.filter(itemTwo => item.data.map(x => x.id).includes(itemTwo.id))
}));
and also
const newArr = [];
arrayOne.map((item, idx) => {
if (arrayTwo.filter(itemTwo => itemTwo.data?.map(x => x.id) === item.id)) {
newArr.push(arrayTwo.data[idx].value);
} else newArr.push(null);
});
To do this you can map arrayTwo and use .find() to search for the ID in arrayOne. I also mapped arrayTwo to the inner object to make the second map more concise.
const arrayOne = [
{id: '110'},
{id: '202'},
{id: '259'}
];
const arrayTwo = [
{data: [{value: 'Alpha',id: '001'}]},
{data: [{value: 'Bravo',id: '202'}]},
{data: [{value: 'Charlie',id: '777'}]},
{data: [{value: 'Delta',id: '202'}]}
];
const result = arrayTwo
.map(obj => obj.data[0])
.map(obj => (arrayOne.find(v => v.id === obj.id) && obj.value) || null)
console.log(result)
Use map to iterate over each element of arr1 and return a new array.
Reassemble the data attribute array of each element in the arr2 array
using map and flat
When arr1 traverses, you can get the current element id, use filter
to filter the combined data array, and return an element array that matches
the current element id.
Based on the case where the id is not matched, use the optional chain operator to get the value.
When returning
if you want to get the element array of the id and
value attributes, use conditional (ternary) operator, when it doesn't match, return the original element,
when it matches, use spread syntax, copy the current element
attribute, and add the value attribute
if you only want to get an
array of matching results, just return the value,
remember to use the optional chain operator to convert the unmatched
value to null.
const arr1 = [
{ id: '110' },
{ id: '202' },
{ id: '259' }
];
const arr2 = [
{ data: [{ value: 'Alpha', id: '001' }] },
{ data: [{ value: 'Bravo', id: '202' }] }
];
const result1 = arr1.map(o1 => {
const data = arr2.map(o2 => o2.data).flat();
const value = data.filter(o2 => o2.id === o1.id)[0]?.value;
return value ? {...o1, value} : o1;
});
const result2 = arr1.map(o1 => {
const data = arr2.map(o2 => o2.data).flat();
const value = data.filter(o2 => o2.id === o1.id)[0]?.value;
return value ?? null;
});
[result1, result2].forEach(r => console.log(JSON.stringify(r)));
You can try this easy line of code :
const arrayOne = [{ id: '110' }, { id: '202' }, { id: '259' }];
const arrayTwo = [{ data: [{ value: 'Alpha', id: '001' }], }, { data: [{ value: 'Bravo', id: '202' }] }];
let result = arrayOne.map(el => {
let found = arrayTwo.find(f => f.data.at(0)?.id == el.id)?.data.at(0)?.value;
return { id: el.id, value: found ?? null};
});
console.log(result);

Update an element from one of multiple arrays

I have an object of 4 arrays like following
const data = {
arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}
Then I need to find an element and update it. Here is what I tried:
const updateElement = (id: number, newName: string) => {
let idx: number;
idx = data.arr1.findIndex((e) => e.id === id);
if (idx !== -1) data.arr1[idx].name = newName;
idx = data.arr2.findIndex((e) => e.id === id);
if (idx !== -1) data.arr2[idx].name = newName;
idx = data.arr3.findIndex((e) => e.id === id);
if (idx !== -1) data.arr3[idx].name = newName;
idx = data.arr4.findIndex((e) => e.id === id);
if (idx !== -1) data.arr4[idx].name = newName;
}
Is there any better way to update an element form multiple arrays than my approach? Suppose that every array has the same element interface.
you can use Object.values() and flat() array for update it :
const data = {
arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}
const updateElement = (id, newName) => {
const values = Object.values(data).flat().find(ele => ele.id === id)
if(values) values.name = newName
}
updateElement(1, 'newName')
console.log(data)

Compare and return boolean if two array of objects has the values or not

I have two array of objects which are like,
let A = [{id: "1"}, {id: "2"},{id: "3" }]
let B = [{id: "3"}, {id: "2"}]
Now, I am iterating over A.
return _.map(A) => ({
id: A.id,
isAvaliable: //This needs to be like weather B includes A on the basis of ID , means does B object has this A client ID if yes then set it true or false
})
So, final object which I will get will be,
const result = [{
{id: "1", isavaliable: false},
{id: "2", isavaliable: true},
{id: "3", isavaliable: true},
}
]
So, How do I achieve this ?
Thanks.
First make an array or Set of the B ids, then you can .map A and set isavailable by whether the id is included in the set:
const A = [{id: "1"}, {id: "2"},{id: "3" }];
const B = [{id: "3"}, {id: "2"}];
const haveIds = new Set(B.map(({ id }) => id));
const result = A.map(({ id }) => ({ id, isavailable: haveIds.has(id) }));
console.log(result);
No need to rely on an external library, Array.prototype.map works just fine.
let A = [{ id: "1" }, { id: "2" }, { id: "3" }];
let B = [{ id: "3" }, { id: "2" }];
const merge = (arr1, arr2) =>
arr1.map((a) => ({
id: a.id,
isAvaliable: !!arr2.find((b) => b.id === a.id),
}));
console.log(merge(A, B));
Use lodash 'find' to check id in array B
const A = [{id: '1'}, {id: '2'}, {id: '3' }];
const B = [{id: '3'}, {id: '2'}];
const C = _.map(A, item => {
return {
id: item.id,
isAvailable: _.find(B, {id: item.id}) ? true : false
};
});

Check and get data from an array in JavaScript

I have an object:
var Obj1 = {id: 1, name: 'Apple'}
And an array object:
var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice}, {'id: 2', 'name': 'Banana'}]
How do I check Obj1.id in ArrObj? And I want the result to be: { id:1, name: 'Apple', 'eat':'rice'}
You can use Array.find():
var Obj1 = {id: 2, name: 'Banana'}
var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice'}, {'id': 2, 'name': 'Banana'}];
var res = ArrObj.find(({id}) => id === Obj1.id );
console.log(res);
You can also use array destructuring way like:
var Obj1 = {id: 2, name: 'Banana'}
var ArrObj = [ {id: 1, name: 'Apple', 'eat': 'rice'}, {'id': 2, 'name': 'Banana'}];
var res = ArrObj.find(({id}) => id === Obj1.id);
console.log(res);
You could also use the filter function like this:
let result = ArrObj.filter(obj => {
return obj.id == Obj1.id
})
Documentation is here: Array.prototype.filter()
all right!
you can also add array and get it by code :
var obj = '{ "name" : "amr" , "age" : "16"}';
var obj1 = JSON.parse(obj);
alert("yourname is : "+obj1.name+" , your age is "+obj1.age);
// it get name > amr and age > 16
it's very easy :)

method find javascript deep array object RN react native

Here is a part of my object
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
const lang = fr;
const anyId = 3;
I don't know why when doing the following:
const result = category[lang].list.find(item => item.id === anyId) console.log(result)
Throws the following:
// undefined category[lang].list.find(item => item.id === anyId) is not
a function, or just undefined
same result for .map or .filter
console.log(category) returns no error
console.log(category[lang]) returns no error
console.log(category[lang].list) returns no error
but anything else will return an error.
It drives me crazy, any help will be highly appreciated.
Use const lang = "fr" instead of const lang = fr, because fr is an undefined variable but "fr" is a string. So you'll get category["fr"] instead of category[fr].
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
const lang = "fr";
const anyId = 3;
const result = category[lang].list.find(item => item.id === anyId)
console.log(result)
You want category.fr not just fr, as the variable fr does not exist.
Now that lang contains your fr object, you can simply do a .find() on lang.list as below:
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'moi'},
{id: 3, label: 'ici'},
{id: 4, label: 'maintenant'},
{id: 5, label: 'demain'},
]}}
// Fill param from a variable, or anything, as long as it's a string:
const param = 'fr';
// Use brackets here, as you want `category.fr` and not `category.param`:
const lang = category[param];
//Or you can simply use:
//const lang = category.fr; //If this is not a parameter, or user input
const anyId = 3;
console.log(lang);
console.log(lang.list.find(item => item.id === anyId));
It works on mdn sandbox
const category = {
fr: {
list: [
{id: 1, label: 'coucou'},
{id: 2, label: 'ici'},
{id: 3, label: 'demain'},
{id: 4, label: 'matin'},
]
}
};
var lang ='fr';
var catID = 3;
console.log(lang);
console.log(catID);
console.log(category);
console.log(category[lang]);
console.log(category[lang].list);
var found = category[lang].list.find(function(element) {
return element.id === catID;
});
console.log(found.label); // demain
just add a return inside the callback function,
but it still doesn't work on react-native
so the problem remains

Categories

Resources