map function save result to an object - javascript

this is what my response looks like
data: [
{
id: 3,
name: "Oliver Green",
email: "test#gmail.com",
contacts: "09179878564"
},
{
id: 2,
name: "Orval McLaughlin",
email: "okoch#example.org",
contacts: "09083692343",
}
]
I used the map function to get the user id and user name, now what I'm trying to do is to save all of the result to an Object
data(){
return {
autoComplete:{},
}
},
let vm = this;
response.data.data.map((user) =>
{
return vm.autoComplete = { [user.id] : user.name};
});
I get the result however I'm only getting one result
autoComplete:Object
2:"Orval McLaughlin"
the result should be
autoComplete:Object
3: "Oliver Green"
2: "Orval McLaughlin"

You need to return the object from map() not the result of an assignment. You are currently assigning vm.autoComplete on each iteration. After you do this you can assign the output of map to the variable you want:
let data = [
{
id: 3,
name: "Oliver Green",
email: "test#gmail.com",
contacts: "09179878564"
},
{
id: 2,
name: "Orval McLaughlin",
email: "okoch#example.org",
contacts: "09083692343",
}
]
let autoComplete = data.map((user) => {
return { [user.id] : user.name};
});
console.log(autoComplete)
EDIT:
If you want an object instead of an array, you should use reduce() because map() always returns an array:
let data = [
{
id: 3,
name: "Oliver Green",
email: "test#gmail.com",
contacts: "09179878564"
},
{
id: 2,
name: "Orval McLaughlin",
email: "okoch#example.org",
contacts: "09083692343",
}
]
let autoComplete = data.reduce((obj, user) =>{
obj[user.id] = user.name; // this assumes user.id will be unique
return obj
}, {});
console.log(autoComplete)

Try this for not wrapping it in array.
response.data.data.map((user) => {
return vm.autoComplete = Object.assign(vm.autoComplete, {[user.id] : user.name}); }

It seems the autoComplete be overwrite for each.
Maybe you can try these:
data(){
return {
autoComplete:{},
}
},
let vm = this;
vm.autoComplete = response.data.data.map((user) => {
return { [user.id] : user.name};
});

Related

get keys from the nested array of objects

I am looking for a function that can mutate my data i.e array of object with a nested object. It will include keys that have object/array values (it should only include keys with immediate string/number/boolean values).
Example
[
{
id: 1,
person1: {
firstname: "test1",
lastname: 'singh',
address: {
state: "maharashtra",
}
}
},
{
id: 2,
person2: {
firstname: "test2",
lastname: 'rathod',
address: {
state: "kerala",
}
}
},
{
id: 3,
person3: {
firstname: "test3",
lastname: 'gokale',
address: {
state: "Tamilnadu",
}
}
}
]
Expected output
[
{
title: 'person1',
value: 'person.id'
},
{
title: 'person1',
value: 'person.firstname'
},
{
title: 'person1',
value: 'person.lastname'
},
{
title: 'person1',
value: 'person.address'
},
{
title: 'person1',
value: 'person.address.state'
},
...sameforOthers
]
Basically, I need a function that will get an array and will return an array of objects as a given above as expected output
Thanks in advance
I have come up with a solution. below is the link for code sandbox for the
https://codesandbox.io/s/heuristic-rubin-yy2cyy?file=/src/index.js:0-213same
const suggestions = [
{
id: 1,
person1: {
id: "1",
firstname: "test1",
lastname: "singh",
address: {
state: "maharashtra"
},
attributeId: "fhgfgh"
}
}
];
const typeList = ["string", "number", "boolean"];
const getLabelValue = (itemList, initalArr, parentId) => {
if (Array.isArray(itemList)) {
itemList.forEach((currentItem, idx) => {
const id = parentId ? `${parentId}.${idx}` : idx;
if (typeList.includes(typeof currentItem)) {
initalArr.push({
title: id,
value: id
});
} else {
getLabelValue(currentItem, initalArr, id);
}
});
} else {
let keys = Object.keys(itemList);
keys.forEach((currentKey) => {
let currentItem = itemList[currentKey];
const id = parentId ? `${parentId}.${currentKey}` : currentKey;
if (typeList.includes(typeof currentItem)) {
initalArr.push({
title: id,
value: id
});
} else {
getLabelValue(currentItem, initalArr, id);
}
});
}
return initalArr;
};
console.log(">>>>>>>>>", getLabelValue(suggestions, [], ""));

return the value of the matching items in an array

I have two arrays that I would like to compare and return a respective value of the ones that match.
Taking the 'id' variable as a reference, I want to return all the matching values of fastFood, but only the 'name'.
My expected result is to return Five Guys and KFC, but instead, it returns the entire object.
let id = ['1234'];
let fastFood = [
{_id:'4391', name: "McDonalds"},
{_id:'7654', name: "Burger King"},
{_id:'8765', name: "Dominos"},
{_id:'1234', name: "Five Guys"},
{_id:'9876', name: "Subway"},
{_id:'1234', name: "KFC"}
];
const findFastFood = ids.filter((item) => {
if (item._id.indexOf(id) !== -1) {
return item.name;
}
});
console.log(findFastFood);
Does this help?
let id = ['1234'];
let fastFood = [{
_id: '4391',
name: "McDonalds"
},
{
_id: '7654',
name: "Burger King"
},
{
_id: '8765',
name: "Dominos"
},
{
_id: '1234',
name: "Five Guys"
},
{
_id: '9876',
name: "Subway"
},
{
_id: '1234',
name: "KFC"
}
];
const findFastFood = fastFood.filter((item) => {
if (id.indexOf(item._id) !== -1) {
return item.name
}
}).map(obj => obj.name);
console.log(findFastFood);

Why async.map returns multiple copies of array?

const async = require('async');
const arr = [
{ name: 'john', id: '1' },
{ name: 'Andrie', id: '2' }]
let collectArr = [];
let data = async.mapLimit(arr, 5, async function (input) {
collectArr.push({ name: input.name, id: input.id });
return collectArr;
})
data.then((result) =>{
console.log('success',result);
}).catch(e => console.log('err'));
So here i am providing array to async.mapLimit without callback and expecting promise here.
Expected Output :- [ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ] ,
Got Result :-
[ [ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ],
[ { name: 'john', id: '1' }, { name: 'Andrie', id: '2' } ] ]
So my question is why it is creating multiple copies of array, how to deal with this?
You are needlessly returning a sub array, and the same array reference each iteration, when all you want is to return the new object.
let data = async.mapLimit(arr, 5, async function (input) {
return { name: input.name, id: input.id };
});
Not sure why you need this to be async

Remove Elements of an array on an object based on outer object property

I have an object that I want to remove elements from one of its' properties that is an array of objects based on a matching property of the outer object.
This uses npm deep-diff to compare the two objects.
My problem is inside of combineDuplicateRecords it compares every record against every record, creating duplicates in the identities array. So identities will end up looking like:
[{
id: "111",
identities: [
{
id: "111"
},
{
id: "111"
},
{
id: "222"
},
{
id: "222"
},
{
id: "333"
},
{
id: "333"
}
]
}]
when I really want it to look like this:
[{
id: "111",
identities:[
{
id: "222"
},
{
id: "333"
}
]
}]
Code:
var requestRecords = [
{
vid: "12345",
id: "12345",
email: "gft#test.com",
firstName: "GrandFathering",
lastName: "TestMN",
postalCode: "55443-2410",
phone: "123-456-7890",
key: "1212"
},
{
vid: "121212",
id: "12222",
email: "g233#test.com",
firstName: "NoMatch",
lastName: "NoMatchFound",
postalCode: "43233-2410",
phone: "123-456-7890",
key: "121233"
},
{
vid: "111",
id: "111",
email: "ffffft#test.com",
firstName: "samebatch",
lastName: "samebatch",
postalCode: "5545",
phone: "123-456-7890",
key: "3333",
},
{
vid: "222",
id: "222",
email: "ffffft#test.com",
firstName: "samebatch",
lastName: "samebatch",
postalCode: "5545",
phone: "123-456-7890",
key: "4444",
},
{
vid: "333",
id: "333",
email: "ffffft#test.com",
firstName: "samebatch",
lastName: "samebatch",
postalCode: "5545",
phone: "123-456-7890",
key: "55",
}
];
combineDuplicateRecords = (arrayOfRecords, prefilter) => {
const recordsToRemove = [];
arrayOfRecords.forEach(firstRecord => {
arrayOfRecords.forEach((secondRecord, index) => {
if (
firstRecord.firstName == secondRecord.firstName &&
firstRecord.lastName == secondRecord.lastName &&
firstRecord.dateOfBirth == secondRecord.dateOfBirth &&
firstRecord.phone == secondRecord.phone &&
firstRecord.postalCode == secondRecord.postalCode &&
firstRecord.id !=
secondRecord.id
) {
const identities = [];
let identity = {};
this.preserveExisitingIdentities(secondRecord, identities);
this.preserveExisitingIdentities(firstRecord, identities);
identity = this.setIdentityDifferencesBetweenRecords(
firstRecord,
secondRecord,
prefilter,
identity
);
identities.push(identity);
firstRecord["identities"] = identities;
recordsToRemove.push(index);
}
});
});
[...new Set(recordsToRemove)].forEach(index => {
arrayOfRecords.splice(index, 1);
});
return arrayOfRecords;
};
preserveExisitingIdentities = (record, identities) => {
if (record.hasOwnProperty("identities")) {
record.identities.forEach(identity => {
identities.push(identity);
});
}
return identities;
};
setIdentityDifferencesBetweenRecords = (
firstIdentity,
secondIdentity,
prefilter,
identity
) => {
const differences = Diff(firstIdentity, secondIdentity, prefilter);
let i = differences.length;
while (i--) {
if (differences[i].path[0] == "vid") {
differences.splice(i, 1);
}
if (differences[i].path[0] == "identities") {
differences.splice(i, 1);
}
//we only want to keep the differences so we remove kind D
if (differences[i]?.kind == "D") {
differences.splice(i, 1);
}
}
differences.forEach(diff => {
identity[diff.path[0]] = diff.lhs;
});
return identity;
};
console.log(JSON.stringify(combineDuplicateRecords(requestRecords)));
grab each inner id and save them in a data structure, then use Array#find to find the entire object and insert it back into identities
const array = [
{
id: "111",
identities: [
{
id: "111"
},
{
id: "111"
},
{
id: "222"
},
{
id: "222"
},
{
id: "333"
},
{
id: "333"
}
]
}
]
const cleanObject = (obj) => {
const allIds = obj.identities.map(({ id }) => id)
const mainId = obj.id
const uniqueIds = new Set(allIds)
uniqueIds.delete(mainId)
const nextIdentities = [...uniqueIds].map(currId => {
return obj.identities.find(({ id }) => currId === id)
})
obj.identities = nextIdentities
return obj
};
const el = array.map(entry => {
return cleanObject(entry)
})
console.log(el)

ES6 array of hashes return unique array of hashes [duplicate]

This question already has answers here:
Create array of unique objects by property
(17 answers)
Closed 3 years ago.
I have an object that looks like this:
const posts = [
{ id: 0, user: { id: 5564, name: 'john'} },
{ id: 1, user: { id: 5564, name: 'john'} },
{ id: 2, user: { id: 5560, name: 'jane'} }
]
I need an array of the unique user hashes like this:
[
{ id: 5564, name: 'john'},
{ id: 5560, name: 'jane'}
]
I'm able to retrieve all the users attributes from the posts array by doing:
const postUsers = posts.map(post => post.user)
which returns:
[
{ id: 5564, name: 'john'},
{ id: 5564, name: 'john'},
{ id: 5560, name: 'jane'}
]
where user john is listed twice
I've been able to get my desired result by doing:
const unique = {};
const uniqueUsers = [];
for(var i in postUsers){
if(typeof(unique[postUsers[i].id]) == "undefined"){
uniqueUsers.push(postUsers[i]);
}
unique[postUsers[i].id] = 0;
};
uniqueUsers
but there must be a cleaner way.
I've also been able to return the unique ids of all users by doing:
var ids = posts.map(post => post.user.id)
var uniqueIds = Array.from(new Set(ids)).sort();
which returns
[5564, 5560]
not sure if that helps. this article helped me a little https://medium.com/tomincode/removing-array-duplicates-in-es6-551721c7e53f
You could take a Map and get only the unique users.
const
posts = [{ id: 0, user: { id: 5564, name: 'john'} }, { id: 1, user: { id: 5564, name: 'john'} }, { id: 2, user: { id: 5560, name: 'jane'} }],
unique = Array.from(posts.reduce((m, { user }) => m.set(user.id, user), new Map).values());
console.log(unique);
If you don't mind using lodash you can do something like
const users = _map.(posts, 'user') // To get the list of users
_.uniqBy(users, 'id') // to get the uniq ones
Put the objects directly in uniqueUsers, then use Object.values() at the end to convert the object to an array.
const posts = [
{ id: 0, user: { id: 5564, name: 'john'} },
{ id: 1, user: { id: 5564, name: 'john'} },
{ id: 2, user: { id: 5560, name: 'jane'} }
];
let uniqueUsers = {};
posts.forEach(({user}) => uniqueUsers[user.id] = user);
uniqueUsers = Object.values(uniqueUsers);
console.log(uniqueUsers);
Use reduce to reduce the array by checking if the value is already in the array. If it is already in the array, return the current state of the array, otherwise add the item to the array.
const posts = [
{ id: 0, user: { id: 5564, name: 'john'} },
{ id: 1, user: { id: 5564, name: 'john'} },
{ id: 2, user: { id: 5560, name: 'jane'} }
]
const r = posts.map(i => i.user).reduce((acc, itm) => {
return !acc.find(i => i.id == itm.id) && acc.concat(itm) || acc
}, [])
console.log(r)

Categories

Resources