Map object inside array in javascript? - javascript

This is my array:
const array = [
{
"fare": "399.00",
"passenger": {
"age": "21",
"gender": "MALE",
"name": "Test1"
},
},
{
"fare": "399.00",
"passenger": {
"age": "21",
"gender": "FEMALE",
"name": "Test2"
},
}
]
How to map the object inside the array, and how to convert the object to the required output
Required output:
Test1(M), Test2(F)
Above contains "name" and gender - if its male then just "M" and if its female just "F"
As of now i tried,
array.map(o => ({ name: o.passenger.name, gender: o.passenger.gender })))
But how to convert this as expected output !

Like this
const array = [{ "fare": "399.00", "passenger": { "age": "21", "gender": "MALE", "name": "Test1" }, }, { "fare": "399.00", "passenger": { "age": "21", "gender": "FEMALE", "name": "Test2" }, } ];
const output = array
.map(({passenger}) => `${passenger.name}(${passenger.gender.slice(0,1)})`)
.join(", ")
console.log(output);

Simply loop your array and make new string:
const array = [
{
"fare": "399.00",
"passenger": {
"age": "21",
"gender": "MALE",
"name": "Test1"
},
},
{
"fare": "399.00",
"passenger": {
"age": "21",
"gender": "FEMALE",
"name": "Test2"
},
}
];
var states = array.map((o) => o.passenger.name + '(' + o.passenger.gender.substring(0, 1) + ')')
console.log(states);

Is this the expected result you want?
const array = [{
"fare": "399.00",
"passenger": {
"age": "21",
"gender": "MALE",
"name": "Test1"
},
}, {
"fare": "399.00",
"passenger": {
"age": "21",
"gender": "FEMALE",
"name": "Test2"
},
}]
const passengers = array.map(o => {
const gender = o.passenger.gender == 'MALE' ? 'M' : 'F';
return o.passenger.name + '(' + gender + ')';
})
console.log(passengers.join(', ')); // Test1(M), Test2(F)

You can convert the objects to strings and join them
const array = [{ "fare": "399.00", "passenger": { "age": "21", "gender": "MALE", "name": "Test1" }, }, { "fare": "399.00", "passenger": { "age": "21", "gender": "FEMALE", "name": "Test2" }, } ]
const output = array.map(o => o.passenger.name + (o.passenger.gender === "MALE" ? "(M)" : "(F)")).join(', ')
console.log(output)

Use map and destructruing
const tests = (arr) =>
arr
.map(
({
passenger: {
gender: [G],
name,
},
}) => `${name}(${G})`
)
.join(", ");
const array = [
{
fare: "399.00",
passenger: {
age: "21",
gender: "MALE",
name: "Test1",
},
},
{
fare: "399.00",
passenger: {
age: "21",
gender: "FEMALE",
name: "Test2",
},
},
];
console.log(tests(array));

Related

How do I map array of objects to an existing array on MongoDB

Please how can I make this work on mongoDB.
For each item in an array, fetch data which contains the item from another collection.
For example:
"users" : [{
"name": "John doe",
"age": 51
},
{
"name": "Jake kim",
"age": 50
},
{
"name": "Jim son",
"age": 51
}]
On another collection I have
"age": [50,51,52,53,54]
Now my desire result is
"50" : [{
"name": "Jake kim",
"age": 50
}],
"51" : [{
"name": "John doe",
"age": 51
},
{
"name": "Jim son",
"age": 51
}]
You can do this. Get the array of users.
const users = [{ "name": "John doe", "age": 51 }, { "name": "Jake kim", "age": 50 }, { "name": "Jim son", "age": 51 }]
Get the array of ages
const age = [50,51,52,53,54]
Then you can map through the array of ages, returning an object that has the user that has the same age, here is the algorithm.
const mapped = age.map(age => {
const user = {}
user[age] = users.find(ob => ob.age === age);
return user;
})
If you print out the mapped result. This is what it will look like, For the ages that we couldn't find their users, they just have an undefined value.
console.log(mapped)
[
{ '50': { name: 'Jake kim', age: 50 } },
{ '51': { name: 'John doe', age: 51 } },
{ '52': undefined },
{ '53': undefined },
{ '54': undefined }
]
I don't think you'll need the age data in your case. However I've provided the both versions which one use the age list but other does not. Please find them below.
const users = [{ "name": "John doe", "age": 51 }, { "name": "Jake kim", "age": 50 }, { "name": "Jim son", "age": 51 }];
const age = [50, 51, 52, 53, 54];
const desired = users.reduce((prev, cur) => {
(prev[cur.age] ?? (prev[cur.age] = [])).push(cur);
return prev;
}, {});
console.log("This is the expected result", desired);
const desired2 = users.reduce((prev, cur) => {
(prev[cur.age] ?? (prev[cur.age] = [])).push(cur);
return prev;
}, age.reduce((prev, cur) => {
prev[cur] = [];
return prev;
}, {}));
console.log("This is the expected result with empty ages", desired2);

Array reduce not giving all the data

let inputArr = [{
"gender": "MALE",
"name": "A",
"age": 20
},
{
"gender": "MALE",
"name": "B",
"age": 12
},
{
"gender": "FEMALE",
"name": "C",
"age": 16
},
{
"gender": "MALE",
"name": "D",
"age": 21
},
{
"gender": "FEMALE",
"name": "E",
"age": 30
}
]
console.log(JSON.stringify(inputArr.reduce((acc, ele) => {
if (acc[ele["gender"]]) {
acc[ele.gender].members.push(ele);
} else {
acc[ele["gender"]] = {
members: []
}
}
return acc;
}, {})))
I am trying to group users on the basis of gender ,using Array.reduce but the output is not showing all the records that are included in the array ,I am not able to understand the isssue here
Your reducer doesn't push the element when it encounter a gender for the first time, so the first user of each gender is missing from your result
let inputArr = [{"gender": "MALE","name": "A","age": 20},{"gender": "MALE","name": "B","age": 12},{"gender": "FEMALE","name": "C","age": 16},{"gender": "MALE","name": "D","age": 21},{"gender": "FEMALE","name": "E","age": 30}]
console.log(JSON.stringify(inputArr.reduce((acc, ele) => {
if (acc[ele["gender"]]) {
acc[ele.gender].members.push(ele);
} else {
acc[ele["gender"]] = {
members: [ele] // initialise the array with the current user
}
}
return acc;
}, {})))
Another solution, but I don't recommend this if performance matter.
let inputArr = [{
"gender": "MALE",
"name": "A",
"age": 20
},
{
"gender": "MALE",
"name": "B",
"age": 12
},
{
"gender": "FEMALE",
"name": "C",
"age": 16
},
{
"gender": "MALE",
"name": "D",
"age": 21
},
{
"gender": "FEMALE",
"name": "E",
"age": 30
}
]
function groupBy(array, field) {
return array.reduce((acc, item) => ({
...acc,
[item[field]]: [...acc[item[field]] || [], item]
}), {})
}
console.log(groupBy(inputArr, "gender"))

How to return multiple values with the method array.from and new set

I would like to know if it is possible from an array of objects to retrieve several unique values with the method array.from new set.
For example :
this.data = [
{
"_id": "5bf57b965401169dd81c2a51",
"age": 35,
"name": "Paige Zamora",
"gender": "female",
"company": "AUTOMON",
"reference_id": "12"
},
{
"_id": "5bf57b96c2c3b88adff4b972",
"age": 40,
"name": "Jennifer Carr",
"gender": "female",
"company": "SYNKGEN",
"reference_id": "11"
},
{
"_id": "5bf57b969dd839926db78767",
"age": 38,
"name": "Weaver Rosales",
"gender": "male",
"company": "ETERNIS",
"reference_id": "10"
},
{
"_id": "5bf57b968c845ea691e76c84",
"age": 31,
"name": "Myers Pickett",
"gender": "male",
"company": "ETERNIS",
"reference_id": "10"
},
{
"_id": "5bf57b96998c44eff083d3fa",
"age": 36,
"name": "Dona Nicholson",
"gender": "female",
"company": "ETERNIS",
"reference_id": "10"
}
]
I would like to retrieve the following unique values: reference_id and the company associated with the reference_id, which would give this:
[{12, AUTOMON}, {11, SYNKGEN}, {10, ETERNIS}]
I thought I would use this method:
const list = Array.from (new Set (this.data.map ({reference_id}) => reference_id)));
what returns :
[12,11,10]
I do not know if this method can be used to return multiple values like the list above ?
You could use a JSON with the wanted data and take then the parsed values as result.
Why a string instead of an object, you may ask. The problem here is every new object with the wanted properties is a new object, and not the same.
Set works wite a single primitive or object and checks, if an object's reference is the same. By taking a string, the value could be checked and you get unique strings in the set. This required to convert the JSON back to an object.
var data = [{ _id: "5bf57b965401169dd81c2a51", age: 35, name: "Paige Zamora", gender: "female", company: "AUTOMON", reference_id: "12" }, { _id: "5bf57b96c2c3b88adff4b972", age: 40, name: "Jennifer Carr", gender: "female", company: "SYNKGEN", reference_id: "11" }, { _id: "5bf57b969dd839926db78767", age: 38, name: "Weaver Rosales", gender: "male", company: "ETERNIS", reference_id: "10" }, { _id: "5bf57b968c845ea691e76c84", age: 31, name: "Myers Pickett", gender: "male", company: "ETERNIS", reference_id: "10" }, { _id: "5bf57b96998c44eff083d3fa", age: 36, name: "Dona Nicholson", gender: "female", company: "ETERNIS", reference_id: "10" }],
unique = Array.from(
new Set(
data.map(({ reference_id, company }) =>
JSON.stringify({ reference_id, company }))
),
json => JSON.parse(json)
);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can also group them in a Map (ignoring any repetitions and where keys are the string representations of reference_id and company) and return an array from its values:
var data = [{
"_id": "5bf57b965401169dd81c2a51",
"age": 35,
"name": "Paige Zamora",
"gender": "female",
"company": "AUTOMON",
"reference_id": "12"
},
{
"_id": "5bf57b96c2c3b88adff4b972",
"age": 40,
"name": "Jennifer Carr",
"gender": "female",
"company": "SYNKGEN",
"reference_id": "11"
},
{
"_id": "5bf57b969dd839926db78767",
"age": 38,
"name": "Weaver Rosales",
"gender": "male",
"company": "ETERNIS",
"reference_id": "10"
},
{
"_id": "5bf57b968c845ea691e76c84",
"age": 31,
"name": "Myers Pickett",
"gender": "male",
"company": "ETERNIS",
"reference_id": "10"
},
{
"_id": "5bf57b96998c44eff083d3fa",
"age": 36,
"name": "Dona Nicholson",
"gender": "female",
"company": "ETERNIS",
"reference_id": "10"
}
];
var res = Array.from(data.reduce((acc, {reference_id, company}) => {
acc.set(`${reference_id},${company}`, {reference_id, company});
return acc;
}, new Map()).values());
console.log(res);
Try this:
this.data.map((el) =>{ return {age: el.age, company: el.company} })
// You get this array
//0: {age: 35, company: "AUTOMON"}
//1: {age: 40, company: "SYNKGEN"}
//2: {age: 38, company: "ETERNIS"}
//3: {age: 31, company: "ETERNIS"}
//4: {age: 36, company: "ETERNIS"}
{12, AUTOMON} doesn't make sense, obj is { key: value, key: value...}

How to add a name for each element of a list in Jackson

Is it possible to set a name for each element of a list in JSON using JACKSON?
For example, I have the following JSON:
{"result": [
{
"name": "ABC",
"age": "20"
},{
"name": "DEF",
"age": "12"
}
]}
But I need this:
{"result": [
person: { // << this is the name
"name": "ABC",
"age": "20"
},
person: {
"name": "DEF",
"age": "12"
}
]}
Thanks to everybody!
UPDATE
Hi people!
I made a mistake! The correct form is the following:
{"result": [
{
person: { // << this is the name
"name": "ABC",
"age": "20"
}
},
{
person: {
"name": "DEF",
"age": "12"
}
}
]}
In plain Javascript, you could use Array#map and return a new object with person property.
var object = { result: [{ name: "ABC", age: "20" }, { name: "DEF", age: "12" }] };
object.result = object.result.map(function (a) {
return { person: a };
});
console.log(object);

Rebuild nested array

I have an nested array that i want to rebuild based on age value:
//Data
data = {"people":
[{"male_1": [
{"name": "Bob" ,"age": "32"},
{"name":"Mike", "age":"31"}
]},
{"female_2": [
{"name":"Jessica", "age": "24"},
{"name":"Ann", "age": "23"}
]}
[{"male_3": [
{"name": "Tom" ,"age": "31"},
{"name":"John", "age":"29"}
]}, ...
]}
New array should looks like:
people = [{"male_1": [
{"name": "Bob" ,"age": "32"}
]},
[{"male_3": [
{"name": "Tom" ,"age": "31"}
]},
{"female_2": [
{"name":"Jessica", "age": "24"}
]}, ...
]}
Based on this example i need to find the largest age of all "persons" then add this person to array then do same with the next one. The age can be same in this case there is no difference who goes first.
With the next function i can find first one and push it to new array, but how find next one?
var age = 0;
data["people"].forEach(function(item) {
for (var key in item) {
if (item.hasOwnProperty(key)) {
item[key].forEach(function(person) {
if (person.age > age) {
age = person.age;
oldest_person = person
}
});
}
}
});
console.log(oldest_person);
here is another interpretation. This one uses the native Array.prototype.sort as the helper function.
var data = { "people": [{ "male_1": [{ "name": "Bob", "age": "32" }, { "name": "Mike", "age": "31" }] }, { "female_2": [{ "name": "Jessica", "age": "24" }, { "name": "Ann", "age": "23" }] }, { "male_3": [{ "name": "Tom", "age": "31" }, { "name": "John", "age": "29" }] }] },
oldies = [],
peopleByAge = data.people.map(function(group){
for( var name in group ){
group[name] = group[name].sort(sortBy('age'));
oldies.push( group[name][0] );
}
return group;
});
// sort by an object key
function sortBy( key ){
return function(a, b){
return parseInt(a[ key ]) < parseInt(b[ key ]);
}
}
document.write('<pre>' + JSON.stringify({ oldies: oldies.sort(sortBy('age')), peopleByAge: peopleByAge }, 0, 2) + '</pre>');
Try this:
var age = 0;
var oldest_person = [];
var data = {"people":
[
{"male_1": [
{"name": "Bob" ,"age": "32"},
{"name":"Mike", "age":"31"}
]},
{"female_2": [
{"name":"Jessica", "age": "24"},
{"name":"Ann", "age": "23"}
]},
{"male_3": [
{"name": "Tom" ,"age": "31"},
{"name":"John", "age":"29"}
]}
]};
data["people"].forEach(function(item) {
for (var key in item) {
if (item.hasOwnProperty(key)) {
var age = 0;
var name = key;
var oldest = null;
item[key].forEach(function(person) {
// Determine the oldest person in each group ("male_1", "female_2", "male_3", ...)
if (person.age > age) {
age = person.age;
oldest = person;
}
});
// Push the oldest person into the 'oldest_person' array
var group = {};
group[name] = [ oldest ];
oldest_person.push(group);
}
}
});
console.log(oldest_person);
You can use some Array methods, like Array.prototype.forEach(), Array.prototype.reduce() and Object.keys().
var data = { "people": [{ "male_1": [{ "name": "Bob", "age": "32" }, { "name": "Mike", "age": "31" }] }, { "female_2": [{ "name": "Jessica", "age": "24" }, { "name": "Ann", "age": "23" }] }, { "male_3": [{ "name": "Tom", "age": "31" }, { "name": "John", "age": "29" }] }] },
people = [];
data.people.forEach(function (a) {
Object.keys(a).forEach(function (k) {
var o = {};
o[k] = a[k].reduce(function (c, d) {
return c.age > d.age ? c : d;
});
people.push(o);
});
});
document.write('<pre>' + JSON.stringify(people, 0, 4) + '</pre>');

Categories

Resources