So, let's suppose I have this:
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' }
];
If I do this:
var officersIds = officers.map(x => [x.name, x.lastName]);
the result of officersIds is gonna be this:
[ "Captain", "Piett" ], [ "General", "Veers" ], [ "Admiral", "Ozzel" ], [ "Commander", "Jerjerrod" ]
right?
So, what I need to do is to put an object on each map iteration so the output is now this, for example:
[["x", "y"], [ "Captain", "Piett" ]],
[["x", "y"], [ "General", "Veers" ]],
[["x", "y"], [ "Admiral", "Ozzel" ]],
[["x", "y"], [ "Commander", "Jerjerrod" ]]
Why do I need this? Better don't ask ;) But it's a complex problem and if you help me solve this simple one I could transfer your solution to my complex problem.
IMPORTANT: Is there a way to do this in one line?
If you simply want to add ['x', 'y'] to the start of the array, you can use the spread operator to make it a one-liner:
var officersIds = [['x', 'y'], ...officers.map(x => [x.name, x.lastName])];
See proof-of-concept below:
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' }
];
var officersIds = [['x', 'y'], ...officers.map(x => [x.name, x.lastName])];
console.log(officersIds);
However, if you want to add ['x', 'y'] to each item in the array, then you should do this instead:
var officersIds = officers.map(x => [['x', 'y'], [x.name, x.lastName]]);
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' }
];
var officersIds = officers.map(x => [['x', 'y'], [x.name, x.lastName]]);
console.log(officersIds);
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' },
];
officers.unshift({ name: x, lastName: y });
var officersIds = officers.map(x => [x.name, x.lastName]);
Or
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' },
];
var officersIds = officers.map(x => [x.name, x.lastName]);
officersIds.unshift(["x", "y" ]);
You could just add the wanted parts to the mapping function.
var officers = [{ id: 20, name: 'Captain', lastName: 'Piett' }, { id: 24, name: 'General', lastName: 'Veers' }, { id: 56, name: 'Admiral', lastName: 'Ozzel' }, { id: 88, name: 'Commander', lastName: 'Jerjerrod' }],
officersIds = officers.map(x => [["x", "y"], [x.name, x.lastName]]);
console.log(officersIds);
Use Map over officers.
var officers = [
{ id: 20, name: 'Captain', lastName: 'Piett' },
{ id: 24, name: 'General', lastName: 'Veers' },
{ id: 56, name: 'Admiral', lastName: 'Ozzel' },
{ id: 88, name: 'Commander', lastName: 'Jerjerrod' }
];
var officersIds = officers.map(x => [["x", "y"], [x.name, x.lastName]]);
console.log(officersIds);
Related
I have an array of objects to be converted to an object with an array of unique values assigned to the same keys.
How can I get this output?
//input
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
//output
let unique = {
id: [1, 2, 3 ,4 ,5],
name: ['Alan', 'John', 'Monica', 'Sandra', 'Jacob'],
surname: ['Davis', 'Doe', 'Bush', 'Back', 'Front'],
age: [34, 35, 25, 23],
isAdmin: ['yes', 'no'],
}
You can use Array.prototype.reduce() and for all of the items iterate over with Array.prototype.forEach() and creating a unique array with Set
Code:
const users = [{ id: 1, name: 'Alan', surname: 'Davis', age: 34, isAdmin: 'yes' },{ id: 2, name: 'John', surname: 'Doe', age: 35, isAdmin: 'no' },{ id: 3, name: 'Monica', surname: 'Bush', age: 25, isAdmin: 'no' },{ id: 4, name: 'Sandra', surname: 'Back', age: 23, isAdmin: 'no' },{ id: 5, name: 'Jacob', surname: 'Front', age: 34, isAdmin: 'yes' },]
const unique = users.reduce((a, c) => (
Object
.entries(c)
.forEach(([k, v]) => a[k] = [...new Set([...(a[k] || []), v])]),
a
), {})
console.log(unique)
Here's one way
Iterate over the keys of the first object in the array to produce a list of keys
Create an array of the corresponding values. Filter the array for dupes.
Wrap the keys and values back into an object
let users = [
{ id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
{ id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
{ id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
{ id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
{ id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];
let unique = Object.fromEntries(
Object.keys(users[0]).map(k =>
[k, users.map(u => u[k]).filter((value, i, arr) => arr.indexOf(value) === i)]
)
);
console.log(unique);
I have the data from the database and I want to push the duplicate value to each array. I attach the exact example I want.
// origin data
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
//result that I want to get
arr1 = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
];
arr2 = [
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
I want to create an array based on the name in this data and push it. Can anyone help?
One way would be to use reduce together with Object.values:
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
}
];
const result = Object.values(data.reduce((acc, cur) => {
const key = `${cur.name}:${cur.age}`;
const prev = acc[key] || [];
return {
...acc,
[key]: prev.concat(cur)
}
}, {}));
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);
I have some data that looks like :
{
_id: "5e985a07feddae7617ac44f6",
age: 24,
eyeColor: "brown",
name: "Cummings Baxter",
gender: "male",
company: "VELOS",
email: "cummingsbaxter#velos.com",
phone: "+1 (907) 482-2451",
tags: ["labore", "elit", "excepteur", "nisi", "mollit", "anim", "aliquip"],
friends: [
{
id: 0,
name: "Sheppard Jensen",
},
],
},
{
_id: "5e985a0709dfa1e6fd93c6ad",
age: 32,
eyeColor: "brown",
name: "Madelyn Dickson",
gender: "female",
company: "KENGEN",
email: "madelyndickson#kengen.com",
phone: "+1 (984) 521-2439",
tags: ["nisi", "veniam", "dolore", "officia", "ex", "non", "pariatur"],
friends: [
{
id: 0,
name: "Bruce Barton",
},
{
id: 1,
name: "Juliet Schmidt",
},
{
id: 2,
name: "Horton Haley",
},
{
id: 3,
name: "Herminia Witt",
},
],
},
{
_id: "5e985a0737e2306e9aef6ecd",
age: 26,
eyeColor: "blue",
name: "Mcguire Mercado",
gender: "male",
company: "LINGOAGE",
email: "mcguiremercado#lingoage.com",
phone: "+1 (963) 450-2194",
tags: ["cupidatat", "occaecat", "amet", "qui", "elit", "esse", "deserunt"],
friends: [
{
id: 0,
name: "Loraine Harper",
},
{
id: 1,
name: "Luann Randall",
},
{
id: 2,
name: "Obrien Rich",
},
{
id: 3,
name: "Noble Wilkerson",
},
],
},
{
_id: "5e985a07148cfba58c860ec2",
age: 26,
eyeColor: "brown",
name: "Marina Porter",
gender: "female",
company: "GORGANIC",
email: "marinaporter#gorganic.com",
phone: "+1 (867) 417-3497",
tags: [
"laborum",
"aliquip",
"sit",
"adipisicing",
"aute",
"cupidatat",
"aliquip",
],
friends: [
{
id: 0,
name: "Blair Hill",
},
{
id: 1,
name: "Ebony Jimenez",
},
],
},
{
_id: "5e985a074984f9f08ccaaa4c",
age: 255,
eyeColor: "green",
name: "Barlow Ferguson",
gender: "male",
company: "TOYLETRY",
email: "barlowferguson#toyletry.com",
phone: "+1 (837) 484-2231",
tags: ["est", "dolor", "minim", "ut", "anim", "culpa", "non"],
friends: [
{
id: 0,
name: "Delacruz Acevedo",
},
{
id: 1,
name: "Gloria Tanner",
},
{
id: 2,
name: "Cantrell Myers",
},
{
id: 3,
name: "Fisher Leonard",
},
{
id: 3,
name: "Gloria Tenner",
},
],
},
];
I want to write a function that recursively filters for desired word and returns object which contains that word.
example : function filterWith(data, "Sheppard Jensen") would return
_id: "5e985a07feddae7617ac44f6",
age: 24,
eyeColor: "brown",
name: "Cummings Baxter",
gender: "male",
company: "VELOS",
email: "cummingsbaxter#velos.com",
phone: "+1 (907) 482-2451",
tags: ["labore", "elit", "excepteur", "nisi", "mollit", "anim", "aliquip"],
friends: [
{
id: 0,
name: "Sheppard Jensen",
},
],
},
I could do this non-recursively but since resursive way could be much more efficient I want to know the way to do this. Would really apreciate any help.
here is a simple way , because JSON.stringify itself use recursively way
function filterWith(data, str) {
return data.filter(each => JSON.stringify(each).indexOf(str) > -1)
}
but you would like to do it by yourself, you can try this way
function filterWith(data, str) {
const isTarget = (_, str) => _.indexOf(str) > -1;
const $filterWith = ($data) => {
if ($data === undefined || $data === null) {
return false;
}
if (typeof $data != 'object' ) {
return isTarget(`${$data}`, `${str}`)
}
if (Array.isArray($data)) {
for (let i of $data) {
if ($filterWith($data[i])) return true
}
}
for (let i in $data) {
if (isTarget(`${data}`, `${i}`) || $filterWith($data[i])) return true
}
return false
}
return data.filter(each => $filterWith(each))
}
I would write a fairly simple recursive check that a given object contains a the string and then write a trivail filter on top of this.
const hasString = (str) => (obj) =>
Array.isArray (obj)
? obj .some (hasString (str))
: Object (obj) === obj
? hasString (str) (Object. values (obj))
: typeof obj === 'string'
? obj .includes (str)
: false
const filterWith = (xs, str) =>
xs .filter (hasString (str))
const input = [{_id: "5e985a07feddae7617ac44f6", age: 24, eyeColor: "brown", name: "Cummings Baxter", gender: "male", company: "VELOS", email: "cummingsbaxter#velos.com", phone: "+1 (907) 482-2451", tags: ["labore", "elit", "excepteur", "nisi", "mollit", "anim", "aliquip"], friends: [{id: 0, name: "Sheppard Jensen"}]}, {_id: "5e985a0709dfa1e6fd93c6ad", age: 32, eyeColor: "brown", name: "Madelyn Dickson", gender: "female", company: "KENGEN", email: "madelyndickson#kengen.com", phone: "+1 (984) 521-2439", tags: ["nisi", "veniam", "dolore", "officia", "ex", "non", "pariatur"], friends: [{id: 0, name: "Bruce Barton"}, {id: 1, name: "Juliet Schmidt"}, {id: 2, name: "Horton Haley"}, {id: 3, name: "Herminia Witt"}]}, {_id: "5e985a0737e2306e9aef6ecd", age: 26, eyeColor: "blue", name: "Mcguire Mercado", gender: "male", company: "LINGOAGE", email: "mcguiremercado#lingoage.com", phone: "+1 (963) 450-2194", tags: ["cupidatat", "occaecat", "amet", "qui", "elit", "esse", "deserunt"], friends: [{id: 0, name: "Loraine Harper"}, {id: 1, name: "Luann Randall"}, {id: 2, name: "Obrien Rich"}, {id: 3, name: "Noble Wilkerson"}]}, {_id: "5e985a07148cfba58c860ec2", age: 26, eyeColor: "brown", name: "Marina Porter", gender: "female", company: "GORGANIC", email: "marinaporter#gorganic.com", phone: "+1 (867) 417-3497", tags: ["laborum", "aliquip", "sit", "adipisicing", "aute", "cupidatat", "aliquip"], friends: [{id: 0, name: "Blair Hill"}, {id: 1, name: "Ebony Jimenez"}]}, {_id: "5e985a074984f9f08ccaaa4c", age: 255, eyeColor: "green", name: "Barlow Ferguson", gender: "male", company: "TOYLETRY", email: "barlowferguson#toyletry.com", phone: "+1 (837) 484-2231", tags: ["est", "dolor", "minim", "ut", "anim", "culpa", "non"], friends: [{id: 0, name: "Delacruz Acevedo"}, {id: 1, name: "Gloria Tanner"}, {id: 2, name: "Cantrell Myers"}, {id: 3, name: "Fisher Leonard"}, {id: 3, name: "Gloria Tenner"}]}]
console .log (filterWith (input, 'Sheppard Jensen'))
.as-console-wrapper {max-height: 100% !important; top: 0}
hasString checks if the input is an array, and if it is, simply recurs over its children until it finds a match, returning false if none match. If the input is an object, we do the same thing with its keys. If the input is a string, we see if it includes the target value. (You might prefer an equality check here.) And if it's not a string, object, or array, it returns false.
filterWith is a simple wrapper that filters an input array using hasString.
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)