Push data to array without index - javascript

I'd like to know how can i add this
{ post_id: 1, text: "text", creation: "date" }
to the "posts" in a array like this
var posts = [
{
post_id: 5,
text: "text",
creation: "date"
},
{
group: "favPosts",
posts: [
{ post_id: 2, text: "text", creation: "date" },
{ post_id: 7, text: "text", creation: "date" }
]
},
{
post_id: 8,
text: "text",
creation: "date"
}
]
I've already tried searching a hundred times but i can't seem to find a answer that suits my case, I've been trying to insert it with commands like slice and push but i can't seem to get it right, i'm still a beginner in javascript.
PS: I've come a solution but i don't think it's very "efficient";
addToGroup("favPosts");
function addToGroup(group) {
for(id in posts) {
if(posts[id].group == group){
posts[id].posts.push({ post_id: 10, text: "did it", creation: "date" });
console.log(posts[id]);
}
}
}

This should work with a push, I don't see why this wouldn't work.
Here is an example, I just used angular to easily display in HTML, not needed for what you are doing:http://plnkr.co/edit/PBCYxfjMqV3jzggMHJZ7?p=preview
var people = [
{
name: "Joe",
surname: "surname"
},
{
group: "name",
people: [{ name: "name", surname: "surname" }, { name: "name", surname: "surname" }]
},
{
name: "James",
surname: "surname"
}
];
var person = { name: "Jennifer", surname: "surname" };
people.push(person);

Related

Fetching data with One to Many/Many to One and Many to Many in TypeORM using javascript

Hi i'am having a problem fetching my data with a profile, kids and toys, which the profile is the parent of the kids and kids is the parent of the toys. I already created fetching the data with "one to many" and "many to one" of profile and kids. Now i want the toys be in the kids attribute.
Here's my table looks like..
Here's my entities..
ProfileEntity.js
var {EntitySchema} = require("typeorm")
module.exports = new EntitySchema({
name "Profile",
tableName: "profile",
columns: {
profile_id: {
primary: true,
type: "integer"
},
name: {
type: "varchar"
},
age: {
type: "integer"
}
},
relations: {
kids: {
target: "Kids",
type: "one-to-many",
inverseSide: "profile"
}
}
});
KidsEntity.js
var {EntitySchema} = require("typeorm")
module.exports = new EntitySchema({
name "Kids",
tableName: "kid",
columns: {
kid_id: {
primary: true,
type: "integer",
},
profile_id: {
primary: true,
type: "integer"
},
kid_name: {
type: "varchar"
},
age: {
type: "integer"
}
},
relations: {
profile: {
target: "Profile",
type: "many-to-one",
joinColumn: {
name: "profile_id"
}
}
}
});
now when i call the
const data = await connection.getRepository("Profile").find({
where: {
name: "Doe"
},
relations: {
kids: true
}
});
it gives me an array like this which is correct
[
{
"profile_id": 1,
"name": "Doe",
"age": 28,
"kids": [
{
"kid_id": 1,
"profile_id": 1,
"kid_name": "Coco",
"age": 2
},
{
"kid_id": 2,
"profile_id": 1,
"kid_name": "Melon",
"age": 3
}
]
}
]
Now i want the Toys data be inside the kids attribute like this.
[
{
"profile_id": 1,
"name": "Doe",
"age": 28,
"kids": [
{
"kid_id": 1,
"profile_id": 1,
"kid_name": "Coco",
"age": 2
"toys": [
{
"toy_id": 1,
"kid_id": 1,
"toy_name": "Golf Set",
"for": "2-3"
},
{
"toy_id": 2,
"kid_id": 1,
"toy_name": "Trucks",
"for": "2-3"
},
]
},
{
"kid_id": 2,
"profile_id": 1,
"kid_name": "Melon",
"age": 3,
"toys": [
{
"toy_id": 3,
"kid_id": 2,
"toy_name": "Barbie",
"for": "3-5"
}
]
}
]
}
]
How can i fetch the data like this? thanks in advance.
It appears that according to your data structure, it is nested relations you are after, not "many-to-many" relations. If you actually wanted many-to-many, then you could have defined a separate "toys" table and then something like "kids_toys" table that establishes a connection between "kids" and "toys".
But for now, following your current setup. First, you can define relations for "toys" like you did for "kids":
module.exports = new EntitySchema({
name "Kids",
...
relations: {
profile: {
...
},
toys: {
target: "Toys",
type: "one-to-many",
inverseSide: "kid"
}
}
Then add definition for the Toys table itself (add other fields properly to Toys.js):
module.exports = new EntitySchema({
name "Toys",
columns: {
toy_id: {
primary: true,
type: "integer",
},
kid_id: {
type: "integer"
},
...
}
...
relations: {
kid: {
target: "Kids",
type: "many-to-one",
joinColumn: {
name: "kid_id"
}
}
}
And finally do the nested query:
const data = await manager.getRepository("Profile").find({
where: {
name: "Doe"
},
relations: {
kids: {
toys: true
}
}
});
Please note that typeorm targets typescript primarily, it's so much easier to work with it in typescript (much less to write). Not sure, why you are defining your entities using plain javascript with typeorm?

Please help to Convert Array to Object

I need to convert an array with only ids and an object with Id & Name need to find object array element from the object and create new Object
App.js:
["111","114","117']
Object:
[
{ id: "111", Name: "Jerry" },
{ id: "112", Name: "Tom" },
{ id: "113", Name: "Mouse" },
{ id: "114", Name: "Minny" },
{ id: "115", Name: "Mayavi" },
{ id: "116", Name: "Kuttoosan" },
{ id: "117", Name: "Raju" }
];
Result Need:
[
{ id: "111", Name: "Jerry" },
{ id: "114", Name: "Minny" },
{ id: "117", Name: "Raju" }
];
const array = ["111", "114", "117"];
const object = [
{ id: "111", Name: "Jerry" },
{ id: "112", Name: "Tom" },
{ id: "113", Name: "Mouse" },
{ id: "114", Name: "Minny" },
{ id: "115", Name: "Mayavi" },
{ id: "116", Name: "Kuttoosan" },
{ id: "117", Name: "Raju" }
];
const result = object.filter(o => array.includes(o.id));
This should give you the result you want, pay attention that what you called object actually is an array of objects, as far as i understood you want keep only the object with an id contained in the first array, so as i shown just filter them
I think you can just use .filter() to achieve the same result.
const targetIds = ["111","114","117"];
const nameObjects = [{id:"111", Name:"Jerry"}, {id:"112", Name:"Tom"}, {id:"113", Name:"Mouse"}, {id:"114", Name:"Minny"}, {id:"115", Name:"Mayavi"}, {id:"116", Name:"Kuttoosan"}, {id:"117", Name:"Raju"}];
const filtered = nameObjects.filter((obj) => targetIds.indexOf(obj.id) !== -1);
// Which should give the result you need
// [{id:"111", Name:"Jerry"}, {id:"114", Name:"Minny"},{id:"117", Name:"Raju"}]
Use the .filter() to get the result
const ids = ["111", "114", "117"];
const nameids = [
{ id: "111", Name: "Jerry" },
{ id: "112", Name: "Tom" },
{ id: "113", Name: "Mouse" },
{ id: "114", Name: "Minny" },
{ id: "115", Name: "Mayavi" },
{ id: "116", Name: "Kuttoosan" },
{ id: "117", Name: "Raju" }
];
const result = nameids.filter(res => ids.includes(res.id));
console.log(result);

How can I get the length of an array of objects which is within an array of objects in javascript?

I have attempted googling this question and have searched through stackoverflow but with no success so as a last resort I'm asking just in case anyone can point me in the right direction.
I have put an example of what my code would look like below.
var objectInfo = [
{
name:"object1",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}],
}, {
name:"object2",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}, {
name: "bricks",
quantity:100
}],
}]
My question is, how would I get the length of my materials object array?
My attempt to achieve this was as follows:
function getMaterialsArrayLength(objName) {
for (i = 0; i < objectInfo.length; i++) {
if (objectInfo[i].name == objName) {
return objectInfo[i].materials.length
}
}
};
However the error returned is "cannot read property materials of undefined". Does anyone have any potential solutions to finding the array length?
I apologise if this has been posted before.
var objectInfo = [{
name: "object1",
materials: [{
name: "wood",
quantity: 10
}, {
name: "stone",
quantity: 16
}],
}, {
name: "object2",
materials: [{
name: "wood",
quantity: 10
}, {
name: "stone",
quantity: 16
}, {
name: "bricks",
quantity: 100
}],
}]
function getMaterialsLength(objName) {
return objectInfo.find(o => o.name === objName).materials.length;
}
console.log(getMaterialsLength('object2'));
Might want to add some error checking.
You cannot get the length of an array that does not exist; more precisely, the element of the array you looking at is undefined, so has no material to find the length of:
Just access the object by its index:
var objectInfo = [
{
name:"object1",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}],
}, {
name:"object2",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}, {
name: "bricks",
quantity:100
}],
}];
console.log("objectInfo[0].materials.length: " + objectInfo[0].materials.length);
console.log("objectInfo[1].materials.length: " + objectInfo[1].materials.length);
Using lodash.js.
var objectInfo = [
{
name:"object1",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}],
}, {
name:"object2",
materials: [{
name: "wood",
quantity:10
}, {
name: "stone",
quantity:16
}, {
name: "bricks",
quantity:100
}],
}];
function getMaterialsLength(objName) {
_.each(objectInfo, function(obj) {
if (obj.name == objName) {
console.log(_.size(obj.materials));
}
});
}
getMaterialsLength('object2');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>

How can get certain field value from dataSource in kendo UI

I have defined dataSource like this:
var dataSource = new kendo.data.DataSource({
data: [
{Id: 1, name: "Jane Doe", description: "some description", numberValue: "3000.00" },
{Id: 2, name: "John Connor", description: "description temp", numberValue: "1800.00" },
{Id: 3, name: "T-100", description: "descr tmp", numberValue: "2200.00"}
],
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number" },
name: { type: "string" },
description: { type: "string" },
numberValue: { type: "number" }
}
}
}
});
How can I get certain field value from dataSource?
For example: I want get value for field numberValue (where Id = 1, or Id = 2 or Id = 3).
If I call dataSource.data.numberValue then nothing happening. Any help really appreciated. Thank you in advance.
dataSource.data is an array obviously.

Sencha Touch2: Display nested Json data in seperate row in list

I am new to sencha touch2, facing problem while displaying nested json data in seperate rows in list.
Here is my Json looks like:
[
{
"work": {
"agent": {
"activeFlag": "false",
"shiftId": "0",
"id": "0",
"deleteFlag": "false"
},
"id": "124",
"status": "Unassigned",
"assignment": {
"pnr": {
"locator": "ABCDEF",
"connectTime": "0",
"id": "0"
},
"id": "123",
"alerts": "Delay",
"customers": [
{
"lastName": "XYZ",
"firstName": "MNO"
},
{
"lastName": "PQR",
"firstName": "STU "
}
]
}
}
},
{
"work": {
"agent": {
"activeFlag": "false",
"shiftId": "0",
"id": "0",
"deleteFlag": "false"
},
"id": "124",
"status": "Unassigned",
"assignment": {
"pnr": {
"locator": "ABCDEF",
"connectTime": "0",
"id": "0"
},
"id": "123",
"alerts": "Delay",
"customers": [
{
"lastName": "ANY",
"firstName": "KLJ"
},
{
"lastName": "CHE",
"firstName": "MAK"
}
]
}
}
}
]
like this i have 30 'work' objects and in 1 'work' i have 1 'customers' array and i have multiple customers inside
I want to show 'customers' in seperate rows in list but am able to show all the customers of single 'work' in one row like.
Output should be:
---------------
delay
First Name: MNO
---------------
delay
First Name: STU
---------------
delay
First Name: KLJ
---------------
delay
First Name: MAK
---------------
here are models.
ModelList.js:
Ext.define('CustomList.model.ModelList', {
extend: 'Ext.data.Model',
xtype:'modelList',
requires:['CustomList.model.Customers'],
config: {
fields:['work'],
proxy:{
type:'ajax',
url:'http://localhost:9091/CustomListJson/app/store/sample.json',
reader:{
type:'json'
}
},
hasMany:{model:'CustomList.model.Customers',
name:'customers'}
}
});
Customers.js:
Ext.define('CustomList.model.Customers', {
extend: 'Ext.data.Model',
config: {
fields: [
'firstName','lastName'
],
belongsTo: "CustomList.model.ModelList"
}
});
Here is my ShowList.js:
Ext.define('CustomList.view.ShowList',{
extend:'Ext.Panel',
xtype:'showList',
config:{
layout:'fit',
styleHtmlContent:'true',
styleHtmlCls:'showListCls',
items:[
{
xtype:'list',
id: 'listitems',
store:'StoreList',
itemTpl:[ '{work.assignment.alerts}<br>',
'<tpl for="work.assignment.customers">',
'firstName: {firstName}<br>',
'</tpl>'
]
// am able get the below values in list
// itemTpl:'{work.assignment.alerts}'
// itemTpl:'{work.assignment.pnr.locator}'
// itemTpl:'{work.agent.activeFlag}'
// itemTpl: '<b>{firstName} {lastName} </b><br>'+'pnr: '+ '{locator} <br>' +
// 'Alerts: '+'{alerts}' +'status: '+'{status} '
}]
}
});
Here is my StoreList.js:
Ext.define('CustomList.store.StoreList', {
extend:'Ext.data.Store',
requires:['Ext.data.reader.Json'],
config:{
model:'CustomList.model.ModelList',
autoLoad:'true'
}
});
Can anyone please help me. Thanks.
Is this what you were after?
download here
This is a really simple mock up but it should help you out, I think you're model associations are confusing things.
List:
Ext.define('MyApp.view.MyList', {
extend: 'Ext.dataview.List',
config: {
store: 'MyJsonStore',
itemTpl: [
'<div><div><h1>{work.assignment.alerts}</h1></div><tpl for="work.assignment.customers"><div>First Name: {firstName}</div></tpl></div>'
]
}
});
store:
Ext.define('MyApp.store.MyJsonStore', {
extend: 'Ext.data.Store',
config: {
data: [
{
work: {
agent: {
activeFlag: 'false',
shiftId: '0',
id: '0',
deleteFlag: 'false'
},
id: '124',
status: 'Unassigned',
assignment: {
pnr: {
locator: 'ABCDEF',
connectTime: '0',
id: '0'
},
id: '123',
alerts: 'Delay',
customers: [
{
lastName: 'XYZ',
firstName: 'MNO'
},
{
lastName: 'PQR',
firstName: 'STU '
}
]
}
}
},
{
work: {
agent: {
activeFlag: 'false',
shiftId: '0',
id: '0',
deleteFlag: 'false'
},
id: '124',
status: 'Unassigned',
assignment: {
pnr: {
locator: 'ABCDEF',
connectTime: '0',
id: '0'
},
id: '123',
alerts: 'Delay',
customers: [
{
lastName: 'ANY',
firstName: 'KLJ'
},
{
lastName: 'CHE',
firstName: 'MAK'
}
]
}
}
}
],
storeId: 'MyJsonStore',
proxy: {
type: 'ajax',
reader: {
type: 'json'
}
},
fields: [
{
name: 'work'
}
]
}
});
If you get the config working like I have then you can gradually add in your models and associations, as-well as your ajax loading, testing all the way, this should help you to discover what the issue is.
Also, you might want to consider using tools like Json Lint when your working with JSON data, the original JSON blob you posted was difficult to read and badly formatted, all of which makes developing more difficult.

Categories