How to get the object array based on value of object in javascript - javascript

I would like to know how to get the object array list based on values matching in javascript
If any of object value matches with parameter, then return that array in javascript.
var objarr = [
{id:1, email: 'xyz#gmail.com', value: 10, name: 'ram'},
{id:2, email: 'xyz#gmail.com', value: 20, name: 'Tom'},
{id:3, email: 'ss#gmail.com', value: 30, name: 'Lucas'},
{id:4, email: 'ct#gmail.com', value: 40, name: 'Chris'},
{id:5, email: 'tam#gmail.com', value: 30, name: 'Lucas Tim'}
]
function getList(val){
var result=[];
var checkdata = objarr.filter(e=>{
if(Object.values(e)===val){
result.push(e);
}
return result;
})
}
console.log(result);
Expected Output:
getList('xyz#gmail.com');
scenario 1:
[
{id:1, email: 'xyz#gmail.com', value: 10, name: 'ram'},
{id:2, email: 'xyz#gmail.com', value: 20, name: 'Tom'}
]
scenario 2:
getList('Chris');
[
{id:4, email: 'ct#gmail.com', value: 40, name: 'Chris'}
]

Your Array.filter function should return either true or false depending on the search criteria.
Object.values returns an Array as output. To check whether a value is in an array, you can use Array.includes.
You should chck for value with Object.values(e).includes(val)
Working Fiddle
var objarr = [
{ id: 1, email: 'xyz#gmail.com', value: 10, name: 'ram' },
{ id: 2, email: 'xyz#gmail.com', value: 20, name: 'Tom' },
{ id: 3, email: 'ss#gmail.com', value: 30, name: 'Lucas' },
{ id: 4, email: 'ct#gmail.com', value: 40, name: 'Chris' },
{ id: 5, email: 'tam#gmail.com', value: 30, name: 'Lucas Tim' }
]
function getList(val) {
var checkdata = objarr.filter(e => {
if (Object.values(e).includes(val)) {
return true;
}
return false;
})
return checkdata;
}
console.log(getList('xyz#gmail.com'));
console.log(getList('Chris'));
Simplified version
var objarr = [
{ id: 1, email: 'xyz#gmail.com', value: 10, name: 'ram' },
{ id: 2, email: 'xyz#gmail.com', value: 20, name: 'Tom' },
{ id: 3, email: 'ss#gmail.com', value: 30, name: 'Lucas' },
{ id: 4, email: 'ct#gmail.com', value: 40, name: 'Chris' },
{ id: 5, email: 'tam#gmail.com', value: 30, name: 'Lucas Tim' }
]
const getList = (val) => objarr.filter(e => Object.values(e).includes(val))
console.log(getList('xyz#gmail.com'));
console.log(getList('Chris'));

You can make use of filter and using Object.values to get all the values of an object and then use some to get the desired result.
ONE LINER
objarr.filter((o) => Object.values(o).some((v) => v === val));
var objarr = [
{ id: 1, email: "xyz#gmail.com", value: 10, name: "ram" },
{ id: 2, email: "xyz#gmail.com", value: 20, name: "Tom" },
{ id: 3, email: "ss#gmail.com", value: 30, name: "Lucas" },
{ id: 4, email: "ct#gmail.com", value: 40, name: "Chris" },
{ id: 5, email: "tam#gmail.com", value: 30, name: "Lucas Tim" },
];
const getList = val => objarr.filter((o) => Object.values(o).some(v => v === val));
console.log(getList("xyz#gmail.com"));
console.log(getList("Chris"));
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

search an item in multidimentionnal array

I'm trying to find an element on a multidimentionnal array usin JAVASCRIPT function, but I get error
This is my array's data:
export const datas = [
{
id: 1,
firstName: 'John',
tables: [
{ ID: 11, title: 'Lorem' },
{ ID: 12, title: 'Ipsum' },
],
},
{
id: 2,
firstName: 'Doe',
tables: [
{
ID: 22,
title: 'Arke',
nodes: [{ name: 'Name1' }, { name: 'Name2' }, { name: 'Name3' }],
},
{ ID: 23, title: 'Korem' },
],
},
{
id: 3,
firstName: 'Brad',
tables: [
{
ID: 30,
title: 'Mern',
nodes: [{ name: 'Name4' }, { name: 'Name5' }, { name: 'Name6' }],
},
{
ID: 31,
title: 'Full',
nodes: [{ name: 'Name7' }, { name: 'Name8' }, { name: 'Name9' }],
},
],
},
];
I've tried a reccursive function but it's not work, this is my code :
export const findById = (arr, id) => {
for (let o of arr) {
if (o.tables.length > 0) {
let a = findById(o.tables.nodes, 'id');
console.log(a);
}
}
};
I want to print the Object with ID 22, the problem is that I don't have the same structure in each dimension, and it still confuse me..
My Input : 22
My output :
{
ID: 22,
title: 'Arke',
nodes: [{ name: 'Name1' }, { name: 'Name2' }, { name: 'Name3' }],
},
Have you an idea how to edit my function to get my input's response ?
Your recursive function wasn't too far off, you need to check if the item as a tables first before recursively calling it again. And then finally just check the ID in the loop.
eg..
const datas=[{id:1,firstName:"John",tables:[{ID:11,title:"Lorem"},{ID:12,title:"Ipsum"}]},{id:2,firstName:"Doe",tables:[{ID:22,title:"Arke",nodes:[{name:"Name1"},{name:"Name2"},{name:"Name3"}]},{ID:23,title:"Korem"}]},{id:3,firstName:"Brad",tables:[{ID:30,title:"Mern",nodes:[{name:"Name4"},{name:"Name5"},{name:"Name6"}]},{ID:31,title:"Full",nodes:[{name:"Name7"},{name:"Name8"},{name:"Name9"}]}]}];
function findById(arr, ID) {
for (const a of arr) {
if (a.tables) {
const r = findById(a.tables, ID);
if (r) return r;
}
if (a.ID === ID) return a;
}
}
console.log(findById(datas, 22));
if you just need the nested data you can use flatMap and find
const findById = (arr, id) =>
arr
.flatMap(d => d.tables)
.find(t => t.ID === id)
const datas = [{
id: 1,
firstName: 'John',
tables: [{
ID: 11,
title: 'Lorem'
},
{
ID: 12,
title: 'Ipsum'
},
],
},
{
id: 2,
firstName: 'Doe',
tables: [{
ID: 22,
title: 'Arke',
nodes: [{
name: 'Name1'
}, {
name: 'Name2'
}, {
name: 'Name3'
}],
},
{
ID: 23,
title: 'Korem'
},
],
},
{
id: 3,
firstName: 'Brad',
tables: [{
ID: 30,
title: 'Mern',
nodes: [{
name: 'Name4'
}, {
name: 'Name5'
}, {
name: 'Name6'
}],
},
{
ID: 31,
title: 'Full',
nodes: [{
name: 'Name7'
}, {
name: 'Name8'
}, {
name: 'Name9'
}],
},
],
},
];
console.log(findById(datas, 22))
js has amazing array options https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
the ones which will help you most are probably:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
here are some examples
// get the base with id 22
const baseWith22ID = datas.filter(f => f.tables.filter(s => s.id = 22))
// (i guess you want this one) get all elements with id 22
const onlyElementsWith22ID = datas.flatMap(f => f.tables.filter(s => s.id = 22))

Return a subarray with a value changed to reflect parent object

I am trying to change the value of single key in an associative array which is inside another assoc array using javascript.
I have an array like this:
let arr = [{
id: 4,
name: 'test',
docs: [{
id: 1,
name: 'abc'
},{
id: 2,
name: 'xyz'
}]
}, {
id: 8,
name: 'test2',
docs: [{
id: 5,
name: 'abc'
},{
id: 7,
name: 'xyz'
}]
}]
I want to change the value of name of xyz to xyz (test), where test is name key of parent object and get final array as Output:
[{
id: 1,
name: 'abc (test)'
},
{
id: 2,
name: 'xyz (test)'
},
{
id: 5,
name: 'abc (test2)'
},
{
id: 7,
name: 'xyz (test2)'
}]
I am using approach.
let docs = new Array();
arr.forEach((item, index) => {
let docx = item.documents.map(item1 => {
item1.name = item1.name + " ("+item.name+")";
});
docs.push(docx);
});
return docs;
this is returning array of undefined array.
Try a flatMap
let arr = [{ id: 4, name: 'test', docs: [{ id: 1, name: 'abc' },{ id: 2, name: 'xyz' }] }, { id: 8, name: 'test2', docs: [{ id: 5, name: 'abc' },{ id: 7, name: 'xyz' }] }]
const output = arr.flatMap(item =>
item.docs.map(({id,name}) => ({ id, name: `${name} (${item.name})` }))
)
console.log(output)
There is an issue in your data, the docs inner array contains an object with duplicate keys:
let arr = [{
id: 4,
name: 'test',
docs: [{
id: 1,
name: 'abc',
id: 2, // <-- duplicate key
name: 'xyz' // <-- duplicate key
}]
},
If I remove the duplication, you can use this code to create a new object with the name value updated to xyz123 if the original value was xyz:
const original = [{
id: 4,
name: 'test',
docs: [{
id: 1,
name: 'abc'
}, {
id: 2,
name: 'xyz'
}]
}, {
id: 8,
name: 'test2',
docs: [{
id: 1,
name: 'abc'
}, {
id: 2,
name: 'xyz'
}]
}];
const updates = original.map(currentObject => {
const newObject = Object.assign(currentObject);
const newDocs = newObject.docs.map(doc => {
const newDoc = Object.assign(doc);
if (newDoc.name === "xyz") {
newDoc.name = "xyz123";
}
return newDoc;
});
newObject.docs = newDocs;
return newObject
});
console.log(updates);

How to flatten the nested Array?

How do I flatten the nested Array in the Array?
Here is the example input Array,
const input = [
{
id: 1,
name: 'Charles',
otherFields: [{
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}]
}, {
id: 4,
name: 'Charles',
otherFields: [{
id: 5,
name: 'Pung',
}, {
id: 6,
name: 'James',
}]
}
]
Output Array I want to get.
[{
id: 1,
name: 'Charles'
}, {
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}, {
id: 4,
name: 'Charles'
}, {
id: 5,
name: 'Pung',
}, {
id: 6,
name: 'James',
}]
I want to somehow get the output in one statement like
input.map((sth) => ({...sth??, sth.field...})); // I'm not sure :(
With flatMap you can take out the otherFields property, and returning an array containing the parent item and the other array:
const input = [{
id: 1,
name: 'Charles',
otherFields: [{
id: 2,
name: 'Pung',
}, {
id: 3,
name: 'James',
}]
}];
console.log(
input.flatMap(({ otherFields, ...item }) => [item, ...otherFields])
);
For more than one level, you could take a recursive approach of flattening.
const
flat = ({ otherFields = [], ...o }) => [o, ...otherFields.flatMap(flat)],
input = [{ id: 1, name: 'Charles', otherFields: [{ id: 2, name: 'Pung' }, { id: 3, name: 'James', otherFields: [{ id: 4, name: 'Jane' }] }] }],
result = input.flatMap(flat);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

how to get last records of unique usernames from an array in java script

I have an Array of Objects Like:
[
{ id: 8, username: 'peter' ,weight:80,date:'2019-10-14'},
{ id: 1, username: 'harry' ,weight:80,date:'2019-01-01'},
{ id: 2, username: 'harry' ,weight:84,date:'2019-02-21'},
{ id: 3, username: 'john' ,weight:80,date:'2019-03-11'},
{ id: 7, username: 'john' ,weight:80,date:'2019-05-25'},
{ id: 4, username: 'peter' ,weight:80,date:'2019-08-06'},
{ id: 5, username: 'peter' ,weight:80,date:'2019-06-11'},
{ id: 6, username: 'harry' ,weight:90,date:'2019-04-03'}
]
and I want last record of every unique user datewise for ex:
[
{ id: 6, username: 'harry' ,weight:90,date:'2019-04-03'},
{ id: 7, username: 'john' ,weight:80,date:'2019-05-25'},
{ id: 8, username: 'peter' ,weight:80,date:'2019-10-14'},
]
in javascript.
You could take a Map and get the values.
var array = [{ id: 1, username: 'harry', weight: 80, date: '2019-01-01' }, { id: 2, username: 'harry', weight: 84, date: '2019-02-21' }, { id: 3, username: 'john', weight: 80, date: '2019-03-11' }, { id: 4, username: 'peter', weight: 80, date: '2019-08-06' }, { id: 5, username: 'peter', weight: 80, date: '2019-06-11' }, { id: 6, username: 'harry', weight: 90, date: '2019-04-03' }, { id: 7, username: 'john', weight: 80, date: '2019-05-25' }, { id: 8, username: 'peter', weight: 80, date: '2019-10-14' }],
result = Array.from(new Map(array.map(o => [o.username, o])).values());
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Maps and Sets inherently only hold unique values. You can use this as following:
var myMap = [
{ id: 1, username: 'harry' ,weight:80,date:'2019-01-01'},
{ id: 2, username: 'harry' ,weight:84,date:'2019-02-21'},
{ id: 3, username: 'john' ,weight:80,date:'2019-03-11'},
{ id: 4, username: 'peter' ,weight:80,date:'2019-08-06'},
{ id: 5, username: 'peter' ,weight:80,date:'2019-06-11'},
{ id: 6, username: 'harry' ,weight:90,date:'2019-04-03'},
{ id: 7, username: 'john' ,weight:80,date:'2019-05-25'},
{ id: 8, username: 'peter' ,weight:80,date:'2019-10-14'},
]
var result = {};
for(i = 0; i < myMap.length; i++){
result[myMap[i]['username']] = myMap[i];
}
console.log(Object.values(result));
Check the array from end for current object username and previous object username. If they are same break the loop, else push in the array.
const input = [
{ id: 1, username: 'harry' ,weight:80,date:'2019-01-01'},
{ id: 2, username: 'harry' ,weight:84,date:'2019-02-21'},
{ id: 3, username: 'john' ,weight:80,date:'2019-03-11'},
{ id: 4, username: 'peter' ,weight:80,date:'2019-08-06'},
{ id: 5, username: 'peter' ,weight:80,date:'2019-06-11'},
{ id: 6, username: 'harry' ,weight:90,date:'2019-04-03'},
{ id: 7, username: 'john' ,weight:80,date:'2019-05-25'},
{ id: 8, username: 'peter' ,weight:80,date:'2019-10-14'},
];
const output = [];
for(let i = input.length-1; i > 0; i--) {
if(input[i].username === input[i-1].username) {
break;
}
output.push(input[i]);
}
console.log(output.sort((a, b) => a.date.localeCompare(b.date.localeCompare)));

How to Flatten Object Underscore with a new Property?

I'm having an array of this:
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
]
How can I use underscore to flatten the age object in the array. The expected result is:
arr == [
{
name: 'John',
age: 'less than 19'
},
{
name: 'Doe',
age: 'more than 19'
}
];
Thanks,
You can try this:
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
Demo:
var arr = [{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
}, {
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}];
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
console.log(result);
I hope this will help you.
using old style :D
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
];
var newArr = [];
arr.forEach(function(item, idx) {
newArr.push({
name: item.name,
age: item.age.value
});
});
console.log(newArr);

Categories

Resources