Transform inherited object to specific key - javascript

I have one object and inside the object, there have roles(array of number) and I want to transform only the roles, it should be an array of objects. see below
current object,
displayConfiguration: {
widgetList: {
widgetName: 'widget tiltle',
entityType: 'Asset',
roles: [202]
},
addIcon: {
fileName: '',
fileDownloadUri: ''
},
displayInfoIcon: {
visible: true,
summaryText: 'info icon text'
},
useFilter: true
}
expected object
displayConfiguration: {
widgetList: {
widgetName: 'widget tiltle',
entityType: 'Asset',
roles: [
{
id: 202
}
]
},
addIcon: {
fileName: '',
fileDownloadUri: ''
},
displayInfoIcon: {
visible: true,
summaryText: 'info icon text'
},
useFilter: true
}

const displayConfiguration = {
widgetList: {
widgetName: 'widget tiltle',
entityType: 'Asset',
roles: [202]
},
addIcon: {
fileName: '',
fileDownloadUri: ''
},
displayInfoIcon: {
visible: true,
summaryText: 'info icon text'
},
useFilter: true
}
const answer = {
...displayConfiguration,
widgetList: {
...displayConfiguration.widgetList,
roles: displayConfiguration.widgetList.roles.map(x => ({id: x}))
}
}
console.log(answer)
Should be rather straight forward, you can use map function to transform array

You can you use .map() function, that will walk through each element and convert your number to object that you need.
const displayConfiguration = {
widgetList: {
widgetName: 'widget tiltle',
entityType: 'Asset',
roles: [202]
},
addIcon: {
fileName: '',
fileDownloadUri: ''
},
displayInfoIcon: {
visible: true,
summaryText: 'info icon text'
},
useFilter: true
};
const roles = displayConfiguration.widgetList.roles;
displayConfiguration.widgetList.roles = roles.map(role => {
return {
id: role
}
})
console.log(displayConfiguration);
The map function creates a new array populated with the results of calling a provided function on every element in the calling array.

Related

Cannot read properties of undefined (reading 'current') I can't get slug from array

current page not displayed
I can't get current slug from array
stack:
backend: Sanity
Frontend: Astro.build
Sanity
import { defineField, defineType } from 'sanity'
export default defineType({
name: 'art',
title: 'Arts',
type: 'document',
fields: [
defineField({
name: 'year',
title: 'Year',
type: 'string',
options: {
hotspot: true,
},
}),
defineField({
name: 'images',
title: 'Arts',
type: 'array',
of: [{
name: 'object',
title: 'object',
type: 'object',
options: {
hotspot: true,
},
fields: [{
name: 'image',
type: 'image',
title: 'image',
},
{
name: 'title',
type: 'string',
title: 'Title',
},
{
name: 'slug',
title: 'Slug',
type: 'slug',
options: {
source: 'title',
maxLength: 96,
},
},
],
}, ],
}),
]
})
Astro
[slug].astro
---
import Layout from '../../layouts/Page.astro'
import { useSanityClient } from "astro-sanity";
export async function getAllArts() {
const query = `*[_type == 'art']`;
const data = await useSanityClient().fetch(query);
return data;
}
export interface Props {
art: any;
}
export async function getStaticPaths() {
const allArtInfo = await getAllArts();
return allArtInfo.map(art => ({params: { slug: art.images.slug.current }, props: {art}}));
}
const { art } = Astro.props;
const seo = {
title: '',
description: '',
}
---
<Layout seo={seo}>
<!-- <h1>{art.title}</h1> -->
</Layout>
Trying to display the current page from the "images" array
As soon as I didn 't write output:
Cannot read properties of undefined (reading 'current')
if add [0] before "images"
return allArtInfo.map(art => ({params: { slug: art.images[0].slug.current }, props: {art}}));
the page is displayed with the current slug. only the first array. how to make everything work fine?
So you have an array of arts and each has an array of images, so you have an array of an array of images that you need to unroll in a single array while keeping reference to the art in each image that you need to pass as prop.
You need a double loop, first loop through all art, in which you have second loop through the images. Then you push a new struct with the second loop image and the loop art, like this
export async function getStaticPaths() {
const allArtInfo = await getAllArts();
const allArtImages = []
allArtInfo.forEach(art => {
art.images.forEach((image)=>{
allArtImages.push({image:image,art:art})
})
});
return allArtImages.map(image => ({params: { slug: image.slug.current }, props: {image.art}}));
}

How to create a dictionary using a for loop in javascript?

I have the following:
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
},
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
I want to follow this structure, but programmatically create each dictionary using each record returned from an API call.
example api call
function getData() {
axios.get(Url + input.value)
.then(function (response) {
json_data = response.data;
});
}
so in python this would probably look something like:
test_list=[]
for item in json_data:
dict = {
name: item.name
path: item.path
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic')
},
test_list.append(dict)
children: test_list
How can I accomplish this in javascript? I'm having a real hard time learning javascript after doing python.
UPDATE:
This is the full code block that I am working with.
export default {
name: 'test',
meta: {
icon: 'fa-android',
expanded: false
},
children: [
{
name: 'test',
path: 'test',
meta: {
label: 'test',
link: 'test'
},
component: lazyLoading('test/Basic')
}
]
}
You were very close:
const children = [];
json_data.forEach(item => {
const dict = {
name: item.name,
path: item.path,
meta: {
label: item.label,
link: item.link,
},
component: lazyLoading('testitem/basic'),
}
children.push(dict);
});

How to get relationship model in Keystone.js

So I try to get 'Pronouns' model from 'Sentence' model from 'TestGenerator' model. And I have id's, but no model.
TestGenerator Model
var TestGenerator = new keystone.List('TestGenerator', {
map: { name: 'title' },
autokey: { path: 'slug', from: 'title', unique: true }
});
TestGenerator.add({
title: { type: String, required: true },
sentences: { type: Types.Relationship, ref: 'Sentence', many: true },
});
TestGenerator.register();
var Sentence = new keystone.List('Sentence', {
map: { name: 'title' },
autokey: { path: 'slug', from: 'title', unique: true }
});
Sentence Model
Sentence.add({
title: { type: String, required: true },
pronouns: { type: Types.Relationship, ref: 'Pronoun', many: true },
verbs: { type: Types.Relationship, ref: 'Verb', many: true },
});
Sentence.relationship({ ref: 'TestGenerator', path: 'sentences' });
Sentence.register();
Ponoun model
var Pronoun = new keystone.List('Pronoun', {
map: { name: 'english' },
autokey: { path: 'slug', from: 'english', unique: true },
});
Pronoun.add({
english: { type: String },
russian: { type: String }
});
Pronoun.relationship({ ref: 'Sentence', path: 'pronouns' });
Pronoun.register();
And my controller
view.on('init', function (next) {
var q = keystone.list('TestGenerator').model.findOne({
slug: locals.filters.test_genetation,
}).populate('sentences');
q.exec(function (err, result) {
locals.testGenerator = result;
locals.current_sentence = result.sentences[0];
locals.data.englishSentence = locals.current_sentence.pronouns;
console.log(locals.data.englishSentence);
next(err);
});
});
And "locals.data.englishSentence" return
["5739bd696ef7d78d16e9e0e5","573ac7645e3d7d7210f1c4be"]
So how I can fix it? Don't understand.
This is related to mongoose, not Keystone actually. Mongoose doesn't provide deep population, you'll need a separate plugin like e.g. mongoose-deep-populate
Have you tried explicitly including pronouns in the populate() call?
var q = keystone.list('TestGenerator').model.findOne({
slug: locals.filters.test_genetation,
})
.populate('sentences sentences.pronouns')
.exec(function (err, result) {
...
});

Ensure only one element of an array has a given property

I want to set a boolean flag on a collection containing an array. As an example of data:
{
_id: "12341234",
name: {
first: 'Jeff',
last: 'Jefferson'
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: true
}, {
address: 'fake#fake.net',
verified: true,
primary: false
}]
}
On every entry in this table, I want the array of emails to only ever have a single entry that is primary: true.
With keys in a table, you can do something like as follows to ensure uniqueness:
Meteor._ensureIndex({ 'name.last': 1 }, { unique: 1 });
Would there be a way to do this on an array in a single entry?
Look at adding custom validation with aldeed:simple-schema, attached to your collection with aldeed:collections2
customUsers = new Mongo.Collection('customUsers');
customUsers.attachSchema(new SimpleSchema({
name: {
type: new SimpleSchema({
first: { type: String},
last: { type: String},
}),
},
emails: {
type: Array,
custom: function() {
if (_.compact(_.pluck(this.value, 'primary')).length !== 1) {
return 'NotOnePrimaryEmail';
}
},
},
'emails.$': {
type: Object,
},
'emails.$.address': {
type: String,
regEx: SimpleSchema.RegEx.Email,
},
'emails.$.verified': {
type: Boolean,
},
'emails.$.primary': {
type: Boolean,
},
}));
SimpleSchema.messages({
NotOnePrimaryEmail: 'You must have one, and only one, email marked as primary',
});
if (Meteor.isServer) {
Meteor.startup(function() {
objValid = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: true,
}, {
address: 'fake#fake.net',
verified: true,
primary: false,
},],
};
objNoPrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: false,
}, {
address: 'fake#fake.net',
verified: true,
primary: false,
},],
};
objMultiplePrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake#fake.org',
verified: true,
primary: true,
}, {
address: 'fake#fake.net',
verified: true,
primary: true,
},],
};
[objValid, objNoPrimary, objMultiplePrimary].forEach(
function(obj) {
try {
customUsers.insert(obj);
console.log('Object was valid, inserted into collection');
} catch (err) {
console.log('Error: ' + err.sanitizedError.reason);
}
}
);
});
}
Output from server console:
~/test/schema$ meteor
[[[[[ ~/test/schema ]]]]]
=> Started proxy.
=> Started MongoDB.
=> Started your app.
=> App running at: http://localhost:3000/
I20151008-15:04:15.280(13)? Object was valid, inserted into collection
I20151008-15:04:15.281(13)? Error: You must have one, and only one, email marked as primary
I20151008-15:04:15.281(13)? Error: You must have one, and only one, email marked as primary

Sencha Javascript Insert to Array First Index

I requesting products from my web service. And i want insert to object array's first index the new item.
my lounch function :
NewMobile.globals = {
mesaj: 'selam',
action: '',
server: '192.168.50.70',
branchCode: '0',
activeTable: '',
activeFolio: '0',
activeTableGroup: '',
activeMustGroup: -1,
activePid: 0,
activeMustGroupString: 0,
activeMustDesc: '',
activeMustArray: [],
activeCampProduct: '',
products: undefined,
rePrint: '',
activePax: 1,
uuid: 'tanimsiz',
activeSkin: 'Krem',
version:undefined,
minVersion:132
};
Its my request.
NewMobile.globals.products = Ext.create('NewMobile.store.PorductStore');
NewMobile.globals.products.setProxy({url: "http://" + NewMobile.globals.server + ':1002/zulu/newmobile/data.aspx?act=getAllProducts'});
NewMobile.globals.products.getProxy();
NewMobile.globals.products.load(function(a, records, c, d, e){
if (c !== true)
{
Ext.Viewport.setMasked(false);
Ext.Msg.alert('uyarı', NewMobile.message.connectionError, Ext.emptyFn);
return;
}
else
{
if(NewMobile.globals.version!==undefined)
{
if(NewMobile.globals.version.MinorRevision>=NewMobile.globals.minVersion)
{
var PopulerProducts=Ext.create('NewMobile.model.Products',
{ id:-65000,
name:"SIK KULLANILANLAR",
groupId:200000,
color:"#FFC673",
type:1,
order:-1,
mustModGroups:0,
mustModGrpCount:0
}
);
NewMobile.globals.products.unshift(PopulerProducts);
}
}
}
});
Product Model :
Ext.define('NewMobile.model.Products', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
config: {
fields: [
{
name: 'id',
type: 'int'
},
{
name: 'name',
type: 'string'
},
{
name: 'groupId',
type: 'int'
},
{
name: 'price',
type: 'float'
},
{
name: 'color'
},
{
name: 'type',
type: 'int'
},
{
name: 'mustModGrpCount'
},
{
name: 'mustModGroups'
},
{
name: 'order',
type: 'int'
},
{
name: 'campCount',
type: 'int'
},
{
name: 'stockCode'
},
{
name: 'populer',
type: 'boolean'
}
]
}
});
Chrome console giving this error.
Object [object Object] has no method 'unshift'
I assume that your NewMobile.store.PorductStore is extending Ext.store.Store. To add items to a store you can either use the add or insert method.
add will add the items to the end of the store so what you want to use is insert and specify the index to be 0. Something like this:
myStore.insert(0, newRecord)
To keep the sorting use addSorted. Inserts the passed Record into the Store at the index where it should go based on the current sort information.
myStore.addSorted(newRecord)
You can read more about how to use stores in Ext.js here: http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.data.Store

Categories

Resources