Parse js table from the file - javascript

I write a programe in JavaScript where I want to add file "tables.js". There are many tables saved in this file.I want to validate the data in each table.
How can I save each of these tables as a separate variable? var people = ...; var city = ...
Part of tables.js file below.
{
people: [{
id: 1,
name: 'Bob',
lastName: 'Asdfg'
}, {
id: 2,
name: 'Carl',
lastName: 'Qwerty'
}],
city: [{
id: 1,
name: 'Prague',
size: 'M',
continent:'Europe'
}, {
id: 1,
name: 'London',
size: 'XL',
continent:'Europe'
}]
}
I have tried JSON.parse so far but unfortunately I can't split this file into separate tables.

What you have to do is extract from the object Keys and allocate them to new variables
There are two ways of doing this . One is dot Notations as per the example and the other is bracket notation which looks like this
let people = data['people'];
let city= data['city'];
var data = {
people: [{
id: 1,
name: 'Bob',
lastName: 'Asdfg'
}, {
id: 2,
name: 'Carl',
lastName: 'Qwerty'
}],
city: [{
id: 1,
name: 'Prague',
size: 'M',
continent:'Europe'
}, {
id: 1,
name: 'London',
size: 'XL',
continent:'Europe'
}]
};
let people = data.people;
let city = data.city;
console.log(people)
console.log('=================')
console.log(city)

Same as above but with ES6 (latest JS version) constants and deconstruct features.
const data = {
people: [{
id: 1,
name: 'Bob',
lastName: 'Asdfg'
}, {
id: 2,
name: 'Carl',
lastName: 'Qwerty'
}],
city: [{
id: 1,
name: 'Prague',
size: 'M',
continent: 'Europe'
}, {
id: 1,
name: 'London',
size: 'XL',
continent: 'Europe'
}]
}
const {people, city} = data
console.log('People:', people)
console.log('City:', city)

Related

How to get the object array based on value of object in 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; }

JS - merge 2 arrays based on properties

I'm trying to merge 2 arrays of objects where the resulting array should have only objects present in array 1 (selectedNames) but with one property from corresponding objects from array 2 (nameDetails). There's one matching (unique) property to match them:
const selectedNames = [
{
id: '11'
name: 'joe',
},
{
id: '22',
name: 'bill',
},
];
const nameDetails = [
{
nameId: '11',
salary: '23422',
location: 'New Jersey',
},
{
nameId: '33',
salary: '23424',
location: 'New York',
},
{
nameId: '22',
salary: '99999',
location: 'Boston',
},
{ nameId: '44',
salary: '323232',
location: 'Chicago',
},
];
The matching property is selectedNames.id === nameDetails.nameId. All entries in selectedNames will definitely be present in nameDetails (but not the other way round). The resulting array should look like that:
[
{
id: '11',
name: 'joe',
salary: '23422',
},
{
id: '22',
name: 'bill',
salary: '99999'
}
]
I'm a bit confused. I know it'll probably consist of .includes() and filter() and ... for merging? I'm not sure how to handle it.
Alternatively, which will probably be much easier, filter the nameDetails array to have only objects with nameId that exists (as id) in selectedNames.
I am a bit confused by your example result. For example where does id: '11111' come from?
Are you looking for something like this maybe?
const selectedNames = [
{
id: '11',
name: 'joe',
},
{
id: '22',
name: 'bill',
},
];
const nameDetails = [
{
nameId: '11',
salary: '23422',
location: 'New Jersey',
},
{
nameId: '33',
salary: '23424',
location: 'New York',
},
{
nameId: '22',
salary: '99999',
location: 'Boston',
},
{ nameId: '44',
salary: '323232',
location: 'Chicago',
},
];
const merged = selectedNames.map(n => {
n.salary = nameDetails.filter(d => n.id === d.nameId)[0].salary;
return n;
});
console.log(merged)
Note: This will change the original selectedNames by adding the salary from the corresponding entry in nameDetails.
Maybe this fits your needs:
selectedNames.map(({ id, name }) => {
let salary = nameDetails.find((nameItem) => nameItem.nameId === id).salary;
return { id, name, salary };
})
Will result in:
[
{
id: '11',
name: 'joe',
salary: '23422',
},
{
id: '22',
name: 'bill',
salary: '99999',
}
]

Replace the records of particular category

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)

Compare two array of objects in javascript/angular and return as soon first condition satisfies (any lodash operator)

Say I have two arrays of objects:
let ar1 = [{
id: 1,
name: 'abc',
job: 'dev'
}, {
id: 2,
name: 'xyz',
job: 'qa'
},{
id: 3,
name: 'pqr',
job: 'dev'
}
];
let arr2 = [{
id: 1,
name: 'abc',
job: 'dev'
},{
id: 2,
name: 'zzz',
job: 'qa'
},{
id: 3,
name: 'pqr',
job: 'dev'
}];
I need to compare them so that I get 'true' and exit the comparison without iterating further as the name is different in the second element between two objects.
I tried with the following code:
private compareObjects(obj1, obj2) {
obj1.forEach((x) => {
obj2.forEach((y) => {
if (x.id === y.id) {
return (!_.isEqual(x, y));
}
});
});
}
I suggest reduce-ing the second array to what's needed for testing the first array: { id : name }. This is a single pass on the second array.
Then use find to test the first array with a single pass that halts on the first mismatch.
let ar1 = [{
id: 1,
name: 'abc',
job: 'dev'
}, {
id: 2,
name: 'xyz',
job: 'qa'
},{
id: 3,
name: 'pqr',
job: 'dev'
}
];
let arr2 = [{
id: 1,
name: 'abc',
job: 'dev'
},{
id: 2,
name: 'zzz',
job: 'qa'
},{
id: 3,
name: 'pqr',
job: 'dev'
}];
let index = arr2.reduce((acc, e) => {
acc[e.id] = e.name
return acc
}, {})
let firstMismatched = ar1.find(e => index[e.id] !== e.name)
console.log(firstMismatched)

Filtering an array by using another array

Array1 = [ name1, name2];
Array2 = [ { name: name1 , id: 1, location: xyz, address: 123 },
{ name: name2 , id: 2, location: abc, address: 456 },
{ name: name3 , id: 3, location: def, address: 234 },
{ name: name4 , id: 4, location: ghi, address: 789 }
];
I have 2 arrays - Array1 and Array2. I want to filter Array2 by using Array1 such that my output comes as - [ { name: name1 , id: 1 }, { name: name2 , id: 2 }]. I tried like this - var ids = _.pluck(_.filter(Array2, a => _.contains(Array1, a.id)), 'id'); but problem with this is it's only giving one thing at a time means I can only get either name or id or location or address at a time but I want to filter name and id both at a time.
Loop over the second array and for each item look if the first contains it. If contains, includes will return true and that element will be in a new array.
Be aware this works only in ES6
var arr1 = [ 'A', 'B'];
var arr2 = [ { name: 'A' , id: 1,address: 123 },
{ name: 'B' , id: 2, address: 456 },
{ name: 'C' , id: 3, address: 234 },
{ name: 'D' , id: 4,address: 789 }
];
var newArr = arr2.filter(item => arr1.includes(item.name)).map(item => ({ name: item.name, id: item.id}));
console.log(newArr);
You could use a hash table for faster check if the wanted names are in the item for filtering.
var array1 = ['name1', 'name2'],
array2 = [{ name: 'name1', id: 1, location: 'xyz', address: 123 }, { name: 'name2', id: 2, location: 'abc', address: 456 }, { name: 'name3', id: 3, location: 'def', address: 234 }, { name: 'name4', id: 4, location: 'ghi', address: 789 }],
result = array2.filter(function (a) {
var hash = Object.create(null);
a.forEach(function (k) { hash[k] = true; });
return function (b) { return hash[b.name]; };
}(array1));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Instead of having to .filter and then .map it, just use .reduce.
Using reduce and includes, you can have something like this:
var Array1 = ["name1", "name2"];
var Array2 = [{
name: "name1",
id: 1,
location: "xyz",
address: 123
},
{
name: "name2",
id: 2,
location: "abc",
address: 456
},
{
name: "name3",
id: 3,
location: "def",
address: 234
},
{
name: "name4",
id: 4,
location: "ghi",
address: 789
}
];
var result = Array2.reduce((arr, cur) => {
if(Array1.includes(cur.name)) {
arr.push({
name: cur.name,
id: cur.id
})
}
return arr
}, [])
console.log(result)
Note, that you can use indexOf instead of includes if needing to support older browsers.

Categories

Resources