Related
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; }
There is one scenario where i need to replace the existing records from cached data with new incoming data source. Looking for the cleaner approach to handle the array operations.
For example:
var userCategory = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'bar',
},
{
id: 'platinum',
name: 'foo',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
Here is new users of particular category
var newPlatinumUsers = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
];
This is the expected result needed:
var expected = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
I tried with filtering all the platinum user from existing records then added the new records but it looks verbose
Is there any cleaner approach like lodash operator??
Thanks for your time!!!
May you are looking for this.
function getUnique(arr){
// removing duplicate
let uniqueArr = [...new Set(arr)];
document.write(uniqueArr);
}
const array = ['acer','HP','Apple','Apple','something'];
// calling the function
getUnique(array);
Verify my answer if it help you.
Please find the Javascript implementation of the same
var userCategory = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'bar', },
{ id: 'platinum', name: 'foo', },
{ id: 'gold', name: 'tom', },
{ id: 'silver', name: 'billy', },
];
var newPlatinumUsers = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'mike', },
];
const result = [...newPlatinumUsers];
userCategory.forEach((node) => {
if(node.id !== 'platinum') {
result.push(node);
}
});
console.log(result);
With this solution you can change more than one category:
var userCategory = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'bar'},
{id: 'platinum',name: 'foo'},
{id: 'gold',name: 'tom'},
{id: 'silver',name: 'billy'},
];
var newUsers = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'mike'},
{id: 'gold',name: 'will'},
{id: 'gold',name: 'jerry'},
];
const idsToReplace = {}
const result = [...newUsers]
result.forEach(u => {
idsToReplace[u.id] = true
})
userCategory.forEach(u => {
if(!idsToReplace[u.id]){
result.push(u)
}
})
console.log(result)
I have given array of objects, something like this
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
]
I need array of arrays filtered by field job
const result = [
{job: 'IT',
workersInfo: [
{id:1, name:'Alex'},
{id:2, name:'Pavel'},
{id:3, name:'Joe'},
{id:4, name:'Josh'}
]
},
{job: 'teacher',
workersInfo: [
{id:5, name: 'Max'},
{id:6, name: 'Sam'}
]
}
]
I tried this, but It's not what I want
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
]
const groupList = data.reduce((reduce, it) => {
reduce[it.job] = reduce[it.job] || [];
reduce[it.job].push({id: it.id, name: it.name});
return reduce;
}, {})
console.log(Object.values(groupList));
How can I add new key workers Info and push info to this field
If you create a new object on each iteration instead of an array you can then use Object.values:
const data = [
{id: 1, name: 'Alex', job: 'IT'},
{id: 2, name: 'Pavel', job: 'IT'},
{id: 3, name: 'Joe', job: 'IT'},
{id: 4, name: 'Josh', job: 'IT'},
{id: 5, name: 'Max', job: 'teacher'},
{id: 6, name: 'Sam', job: 'teacher'}
];
const groupList = data.reduce((acc, { job, id, name }) => {
acc[job] = acc[job] || { job, workersInfo: [] };
acc[job].workersInfo.push({ id, name });
return acc;
}, {})
console.log(Object.values(groupList));
Example below
const data = [
{ id: 1, name: "Alex", job: "IT" },
{ id: 2, name: "Pavel", job: "IT" },
{ id: 3, name: "Joe", job: "IT" },
{ id: 4, name: "Josh", job: "IT" },
{ id: 5, name: "Max", job: "teacher" },
{ id: 6, name: "Sam", job: "teacher" },
];
const output = data.reduce((acc, o) => {
const index = acc.findIndex(a => a.job === o.job);
if (index !== -1) {
acc[index].workersInfo.push({ id: o.id, name: o.name });
} else {
acc.push({
job: o.job,
workersInfo: [{ id: o.id, name: o.name }],
});
}
return acc;
}, []);
console.log(output);
Would something like this work ?
const groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}```
It would be more efficient and comprehensible if instead of having a structure like Array<{job: string, workForce: Array}>, you had something like {[job: string]: Array}
var data = [
{ id: 1, name: 'Alex', job: 'IT' },
{ id: 2, name: 'Pavel', job: 'IT' },
{ id: 3, name: 'Joe', job: 'IT' },
{ id: 4, name: 'Josh', job: 'IT' },
{ id: 5, name: 'Max', job: 'teacher' },
{ id: 6, name: 'Sam', job: 'teacher' }
];
var jobs = data.reduce(function (result, person) {
var jobList = result[person.job];
if (!jobList) {
jobList = [];
result[person.job] = jobList;
}
jobList.push(person);
return result;
}, {});
console.log(jobs);
Trying to generate dropdown with deep nested elements.
Incoming data:
111: {id: 111, name: '111' },
222: {id: 222, name: '222' },
333: {id: 333, name: '333', parent: {id: 222} },
444: {id: 444, name: '444', parent: {id: 333} },
555: {id: 555, name: '555' }
I know only parent and I want to generate a tree for React template.
It's going to be like this:
result:
[{
id: 111,
name: '111'
},
{
id: 222,
name: '222',
children: [{
id: 333,
name: '333',
parent: {
id: 222
},
children: [{
id: 444,
name: '444',
parent: {
id: 333
}
}]
}
]
},
{
id: 555,
name: '555'
}
]
You could take temporary object for keeping all references to the same id and build a tree with the parts.
This works for unsorted data as well.
var data = { 111: { id: 111, name: '111' }, 222: { id: 222, name: '222' }, 333: { id: 333, name: '333', parent: { id: 222 } }, 444: { id: 444, name: '444', parent: { id: 333 } }, 555: { id: 555, name: '555' } },
tree = function (object, root) {
var r = [], o = {};
Object.keys(object).forEach(function (k) {
var id = object[k].id;
o[id] = Object.assign(o[id] || {}, object[k]);
if (o[id].parent === root) {
r.push(o[id]);
} else {
o[o[id].parent.id] = o[o[id].parent.id] || {};
o[o[id].parent.id].children = o[o[id].parent.id].children || [];
o[o[id].parent.id].children.push(o[id]);
}
});
return r;
}(data, undefined);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I take a time for make a demo, but look at your object is worg no passed any json validator.
var _data = [{
id: '111',
name: '111'
}, {
id: '222',
name: '222',
children: [
{
id: '333',
name: '333',
parent: {
id: '222'
},
children: [
{
id: '444',
name: '444',
parent: {
id: '333'
}
}
]
}]
}
];
console.log(_data);
function make(arr){
var _arr = [];
function _do(arr, _parent){
for(var i=0; i<arr.length;i++){
var _o = {
id: arr[i].id,
name: arr[i].name
};
if(_parent){
_o.parent = _parent;
}
if(arr[i].children){
_do(arr[i].children, arr[i].id);
}
_arr[arr[i].id] = _o;
}
}
_do(arr);
return _arr
};
console.log(make(_data));
You can try following. You can solve n level nesting with it.
var obj = {
111: {id: 111, name: '111' },
222: {id: 222, name: '222' },
333: {id: 333, name: '333', parent: {id: 222} },
444: {id: 444, name: '444', parent: {id: 333} },
555: {id: 555, name: '555' }
};
// Iterate over the object keys and create the tree and only push items which have no parent in response
var response = [];
Object.keys(obj).forEach(function(key) {
var item = obj[key];
if (item.parent) {
obj[item.parent.id].children = obj[item.parent.id].children || [];
obj[item.parent.id].children.push(obj[key]);
} else {
response.push(obj[key]);
}
});
console.log(response);
I have an array of person objects and I want to update one of object in place.
persons: [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 13
}, {
id: '3',
name: 'David',
age: 14
}]
The function I have is:
function updatePersonsWith(id, propName, value) {
this.persons.???
}
The arguments passed are id of the person I want to update, propName is the properties of person object, can be id, name or age, value is the value I want to replace with.
I want to find an object by it's id and update only this object of the array.
updatePersonsWith(2, age, 16)
The result would be:
persons: [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 16
}, {
id: '3',
name: 'David',
age: 14
}]
Could be ES6 or using lodash.
Try:
let person = this.persons.find((person) => {
return person.id === id;
});
if (person && person[propName]) {
person[propName] = value;
}
Working example:
var persons = [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 13
}, {
id: '3',
name: 'David',
age: 14
}];
function update(id, prop, val) {
var person = persons.find(function(p) {
return p.id === id;
});
if (person && person[prop]) {
person[prop] = val;
}
}
update('1', 'age', 77);
console.log(persons[0].age);
You can use this:
let persons = [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 13
}, {
id: '3',
name: 'David',
age: 14
}];
function updatePersonsWith(id, propName, value) {
let item = persons.find((v) => {
return v.id == id;
});
if (item && item.hasOwnProperty(propName)) {
item[propName] = value;
}
};
updatePersonsWith(2, 'age', 16);
console.log(persons)
Using lodash, you can do like,
function updatePersonsWith(id, propName, value) {
var match = _.find(persons , function(person) { return person.id === id });
if(match)
match[propName] = value;
}