Angularjs array of nested objects from array - javascript

I have an array of position and nested user objects like so:
[
position: {
title: Developer,
user: { name: Albert }
},
position: {
title: CEO,
user: { name: Smith }
}
]
How do I get an array of [user, user] with Angularjs?

Assuming this is pseudo-code (as it's missing a few { and } and you'd need variables called Developer, Albert, CEO & Smith - I've fixed these in the working example) you can use Array.map:
var arr = [{
Position0: {
title: Developer,
user: { name: Albert }
},
{
Position1 : {
title: CEO,
user: { name: Smith }
}
}];
var result = arr.map(function(val, idx) {
return val["Position" + idx].user.name;
});
Working Example

I just tried this code, and works ...
var positions, users;
users = [];
positions = [
{
title: 'Developer',
user: { name: 'Albert' }
},
{
title: 'CEO',
user: { name: 'Smith' }
}
];
angular.forEach(positions, function(position) {
users.push(position.user);
});
console.log(users);

Firstly this thing does not need angularjs.
The way you can do that is using for each loop:
var users = [];
var positions = [{
Position0: {
title: 'Developer',
user: { name: 'Albert' }
},
Position1 : {
title: 'CEO',
user: { name: 'Smith' }
}
}]
for(var i =0; i< positions.length; i++){
for(var j in positions[i]){ //used to loop on object properties
if(positions[i].hasOwnProperty(j)){ //checking if the property is not inherited
if(positions[i][j].user){ //checking if the property exist, then only will push it to array, so that array doesnot have undefined values
users.push(positions[i][j].user);
}
}
}
}
users array will have the users.

Use angular.forEach():
var arr1=[]
var arr=[
position: {
title: Developer,
user: { name: Albert }
},
position: {
title: CEO,
user: { name: Smith }
}
];
angular.forEach(arr,function(value,key){
arr1[key]=value.position.user;
});
console.log(arr1);

Related

Javascript - transforming an object of array list to new formated one?

I'm trying to transform an object contain array to another one with javascript. Below is an example of the object field and what the formatted one should look like.
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
I need The new Fields to looks like this
let newFields = {
name: 'GAME',
tags:[
{ name: 'playPES', value: "{{PES}}" },
{ name: 'playFIFA', value: "{{FIFA}}" }
]},
One contributor suggested me a method like this but i think something need to modify in it but couldn't figure it out.
export const transform = (fields) => ({
tags: Object .entries (fields) .map (([name, innerFields]) => ({
name,
tags: innerFields.map(({code, title: title: {en})=>({name: en, value: code}))
}))
});
// newFields= transform(Fields)
I'm new working with javascript so any help is greatly appreciated, Thanks.
const transform = (o) => {
return Object.entries(o).map((e)=>({
name: e[0],
tags: e[1].map((k)=>({name: (k.title)?k.title.en:undefined, value: k.code}))
}))[0]
}
console.log(transform({
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
}))
Using the entries method you posted:
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
// 1. Obtain keys and values from first object
Fields = Object.entries(oldFields);
// 2. Create new object
const newFields = {};
// 3. Create the name key value pair from new Fields array
newFields.name = Fields[0][0];
// 4. Create the tags key value pair by mapping the subarray in the new Fields array
newFields.tags = Fields[0][1].map(entry => ({ name: entry.title.en, value: entry.code }));
Object.entries(Fields) will return this:
[
"GAME",
[TagsArray]
]
And Object.entries(Fields).map will be mapping this values.
The first map, will receive only GAME, and not an array.
Change the code to something like this:
export const transform = (Fields) => {
const [name, tags] = Object.entries(Fields);
return {
name,
tags: tags.map(({ code, title }) => ({
name: title.en,
value: code
}))
}
}
Hope it help :)
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
let newFields = {
name: 'GAME',
tags:[
{ name: 'playPES', value: "{{PES}}" },
{ name: 'playFIFA', value: "{{FIFA}}" }
]
}
let answer = {
name: "Game",
tags: [
]
}
Fields.GAME.map(i => {
var JSON = {
"name": i.title.en,
"value": i.code
}
answer.tags.push(JSON);
});
console.log(answer);
I think that this is more readable, but not easier... If you want the result as object you need to use reduce, because when you do this
Object.keys(Fields)
Your object transform to array, but reduce can change array to object back.
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
const result = Object.keys(Fields).reduce((acc, rec) => {
return {
name: rec,
tags: Fields[rec].map(el => {
return {
name: el.title.en,
value: el.code
}
})
}
}, {})
console.log(result)
let Fields = {
GAME: [
{ code: '{{PES}}', title: { en: "playPES"} },
{ code: '{{FIFA}}', title: { en: "playFIFA " } },
]
};
const transform = (fields) => ({
tags: Object .entries (fields) .map (([name, innerFields]) => ({
name,
tags: innerFields.map(({code, title: title,en})=>({name: title.en, value: code}))
}))
});
//check required output in console
console.log(transform(Fields));

Omitting one or multiple values in javascript using lodash

I have a complex structure and I want to omit some properties from this structure for final value
let ListofWorlds = {
listOfCountries: [{
add: [{
id: 1,
updated: {
areacode: 123,
city: {
city: {'Austrailia'},
houses: {1000}
}
}
}], remove: []
}]
}
I want to omit city property from this structure and need this
let ListofWorlds = {
listOfCountries: [{
add: [{
id: 1,
updated: {
areacode: 123
}
}], remove: []
}]
}
This is what I have tried
let newListOfWorls = _.map(ListofWorlds, function (worlds) {
return _.omit(worlds, ['city']); })
Appreciate the help and knowledge
This is what i have tried.
let ListofWorlds = {
listOfCountries: [{
add: [{
id: 1,
updated: {
areacode: 123,
city: {
city: 'Austrailia',
houses: 1000
}
}
}], remove: []
}]}
const newList = ListofWorlds.listOfCountries.map(arr=>{
arr.add.forEach((item,index)=>{
arr.add[index] = _.omit(item,'updated.city')
})
return arr
})
Probably not the best way to do it, but hey it works, and why your code doesn't work probably you mapped an Object ListofWorlds and you need to be specific which field you want to be omitted

Flattened Array with Objects

I'm certain this question is very common, but I can't seem to find a robust answer for my use case.
I have an Array of objects with nesting in two levels. Here is an example of the array:
let array = [
{ company: 'CompanyName1',
child: [
{ title: 'title1a',
baby: [
{ title: 'title1ab' },
{ title: 'title1abc' }
]
},
{ title: 'title2a',
baby: [
{ title: 'titleb2abcd' },
{ title: 'titleb2abcde' }
]
}
]
},
{ company: 'CompanyName2',
child: [
{ title: 'title2b',
baby: [
{ title: 'titleb3ab' },
{ title: 'titleb3abc' }
]
}
]
}
]
And this is my expected Array:
let newArray = [
{
company: 'companyName1',
child_title_0: 'title1a',
child_title_1: 'title1a',
child_baby_0: 'title1ab',
child_baby_1: 'title1abc',
child_baby_2: 'title1abcd',
child_baby_3: 'title1abcde',
},
{
company: 'companyName2',
child_title_0: 'title2b',
child_baby_0: 'titleb3ab',
child_baby_1: 'titleb3abc',
}
]
Basically I need to flatten each of the top level objects of the array. Since the nested objects have the same keys (follow a model, and are dynamic -- some items have 10 nested objects, some 0, etc.) I have to dynamically generate each of the new keys, possibly based in the index of the loops.
Any help -- direction is appreciated.
Thanks!
You can use the map function to return a manipulated version of each object in the array.
let results = [
{
company: 'CompanyName1',
child: [
{
title: 'title1a',
baby: [
{ title: 'title1ab' },
{ title: 'title1abc' }
]
},
{
title: 'title2a',
baby: [
{ title: 'titleb2abcd' },
{ title: 'titleb2abcde' }
]
}
]
},
{
company: 'CompanyName2',
child: [
{
title: 'title2b',
baby: [
{ title: 'titleb3ab' },
{ title: 'titleb3abc' }
]
}
]
}
];
let flattened = results.map(company => {
let childCount = 0, babyCount = 0;
company.child.forEach(child => {
company['child_title_'+childCount] = child.title;
child.baby.forEach(baby => {
company['child_baby_'+babyCount] = baby.title;
babyCount++;
});
childCount++;
});
delete company.child;
return company;
});
console.log(flattened);

Sails.js: Bootstrap encountered an error

I have the following code in my /config/bootstrap.js that inserts some dummy data for development.
/* global User */
/* global Category */
var insertDummyUsers = function() {
sails.log.info('Inserting dummy users');
var users = [
{ email: 'test#test.com' },
{ email: 'test1#testdomain.gr' },
{ email: 'test2#cnn.com'}
];
return User.create(users);
};
var insertDummyCategories = function() {
sails.log.info('Inserting dummy categories');
var categories = [
{ name: 'Furniture' },
{ name: 'Lighting' },
{ name: 'Computers' },
{ name: 'Networking' },
{ name: 'Telecommunications' },
{ name: 'TV & Audio' }
];
return Category.create(categories);
};
module.exports.bootstrap = function(cb) {
User.count().then(function(err,count){
if (count > 0) {
cb();
} else {
// Insert some dummy users
insertDummyUsers()
.then(insertDummyCategories)
.then(cb);
}
});
};
When I lift the app I am getting:
info: Inserting dummy users
info: Inserting dummy categories
error: Bootstrap encountered an error: see(below)
error: [ { name: 'Networking, id: 4, createdAt: ..., updatedAt: ... }]
[... so on]
However I can see that the data is being persisted in the database but the app is not getting lifted.
What's going on here? It really gives no clue.
EDIT
migrate: is set to drop
The Category model is defined as follows:
module.exports = {
attributes: {
name: {
type: 'string'
},
/* Associations */
subcategories: {
collection: 'Subcategory',
via: 'parentCategory'
}
}
};
I find this really bizarre, when I edit your create function like below. It works even when the callback function is empty.
I'll have to look a bit more, but this could be a bug that needs to be reported.
return Category.create(categories, function(err, returnModel) {
sails.log.debug('This should work!!! -- Error : ' + err + 'model : ' +
returnModel); });

Ordering in javascript

How easy/hard is it to order collections in javascript (alphabetical and numerically).
Say I have a collection like:
var map = {
user: { id: "23434", username: "mrblah" },
user: { id: "1010", username: "johnskeet" }
};
And I want to order the collection by id and username.
Update
correction thanks:
var map = [ { id: "23434", username: "mrblah" }, { id: "1010", username: "johnskeet" } ];
var map = {
users: [
{ id: "23434", username: "mrblah" },
{ id: "1010", username: "johnskeet" }
]
};
map.users.sort(function(a, b) {
return a.id - b.id;
});
map.users.sort(function(a, b) {
return a.username.localeCompare(b.username);
});
You want your object to be an array:
var map = [
{ id: "23434", username: "mrblah" },
{ id: "1010", username: "johnskeet" },
{ id: "1220", username: "alohaguy" }
];
We need a utility to display the usernames in order so we can test our work:
var displayUsernames = function(map) {
var out = [];
for (var i=0;i<map.length;i++) {
out.push((map[i].username));
}
alert(out.join(', '));
};
If we use it: displayUsernames(map); we get mrblah, johnskeet, alohaguy
Since it's an array, so we can use .sort(), like this: map.sort();, but if we do that we still get:
mrblah, johnskeet, alohaguy
...from displayUsernames(map); because the array of objects can't be sorted the same way as if it were an array of numbers or strings.
However, if we pass the sort() function a comparison function...
var myCompareFunction = function(a, b) {
return a.username.localeCompare(b.username);
};
Then pass it into map.sort()
map.sort(myCompareFunction);
Now, when we display it again with displayUsernames(map); we get alohaguy, johnskeet, mrblah
Hope that helps.

Categories

Resources