knockout - how to use option and foreach bindings together - javascript

I have an ajax data that comes from server and with this data i should generate select boxes.
please look at this code:
var dataCameFromServer = {
foo: "1",
bar: "sag",
results: [
{
slectedBoxID: null,
selectBoxOptions: [
{
id: 1,
name: "mosi"
},
{
id: 2,
name: "azi"
},
{
id: 3,
name: "mom"
},
{
id: 4,
name: "dad"
}
]
},
{
slectedBoxID: 2,
selectBoxOptions: [
{
id: 1,
name: "tehran"
},
{
id: 2,
name: "masal"
},
{
id: 3,
name: "gilan"
},
{
id: 4,
name: "rasht"
}
]
},
{
slectedBoxID: 1,
selectBoxOptions: [
{
id: 1,
name: "adidas"
},
{
id: 2,
name: "nike"
},
{
id: 3,
name: "rebook"
},
{
id: 4,
name: "puma"
}
]
}
]
};
function selectViewModel() {
var self = this;
this.data = ko.observable(dataCameFromServer);
this.sbValue = ko.observableArray();
ko.computed(function() {
$.each(self.data().results, function(i,v) {
self.sbValue.push(v.slectedBoxID);
});
});
ko.computed(function(){
console.log(self.sbValue());
});
}
ko.applyBindings(new selectViewModel(), $("#wrapper")[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapepr">
<!-- ko with: data -->
<!-- ko foreach : results -->
<select data-bind="options:selectBoxOptions,optionsText: 'name',optionsValue: 'id',value: $root.sbValue()[$index],optionsCaption: 'Choose...'"></select>
<!-- /ko -->
<!-- /ko -->
</div>
I want my select boxes by default selected by the option that is in slectedBoxID and if my selectbox changed then the value of that corresponding slectedBoxIDchange.
is there any advice to do that?
p.s: I don't know how many results come from the server, it's not just this three results!

simplest way is to use ko.mapping plugin
or you can manually make each array object properties to observable.
var dataCameFromServer = { foo: "1", bar: "sag", results: [{ slectedBoxID: null, selectBoxOptions: [{ id: 1, name: "mosi" }, { id: 2, name: "azi" }, { id: 3, name: "mom" }, { id: 4, name: "dad" } ] }, { slectedBoxID: 2, selectBoxOptions: [{ id: 1, name: "tehran" }, { id: 2, name: "masal" }, { id: 3, name: "gilan" }, { id: 4, name: "rasht" } ] }, { slectedBoxID: 1, selectBoxOptions: [{ id: 1, name: "adidas" }, { id: 2, name: "nike" }, { id: 3, name: "rebook" }, { id: 4, name: "puma" } ] } ] };
function selectViewModel() {
var self = this;
// using ko.mapping
this.data = ko.mapping.fromJS(dataCameFromServer);
this.sbValue = self.data.results().map(v => v.slectedBoxID);
}
ko.applyBindings(new selectViewModel(), $("#wrapper")[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div id="wrapepr">
<!-- ko with: data -->
<!-- ko foreach: results -->
<select data-bind="options:selectBoxOptions,optionsText: 'name',optionsValue: 'id',value: slectedBoxID,optionsCaption: 'Choose...'"></select>
<!-- /ko -->
<!-- /ko -->
</div>
<pre data-bind="text: ko.toJSON(sbValue, null, 2)"></pre>

Related

JavaScript - Is there a simple way to get the values for every occurrence of a specific key in nested JSON

I have a JSON structure similar to this:
[
{
cells: [
{ id: "1", cellType: 3, widget: { id: 1, description: "myDesc"} },
{ id: "2", cellType: 4, widget: { id: 2, description: "myDesc2"} }
]
},
{
cells: [
{ id: "3", cellType: 5, widget: { id: 3, description: "myDesc3"} }
]
},
...
]
How do I get the value of every widget into a separate array using EcmaScript (or anything that's available in Angular 2+), and without using a library (including JQuery)? I need a final array like this:
[
{
id: 1,
description: "myDesc"
},
{
id: 2,
description: "myDesc2"
},
...
]
Update
(and thanks to #Felix Kling for the 1st part) - I found I can get all of the widgets with this:
JSON.parse(json)[0].forEach( c => c.cells.forEach( c2 => console.log(c2.widget)));
You can use .map() with .reduce()
let input = [
{
cells: [
{ id: "1", cellType: 3, widget: { id: 1, description: "myDesc"} },
{ id: "1", cellType: 4, widget: { id: 2, description: "myDesc2"} }
]
},
{
cells: [
{ id: "3", cellType: 5, widget: { id: 3, description: "myDesc3"} }
]
},
];
let result = input.reduce((result, current) => {
return result.concat(current.cells.map(x => x.widget));
}, [])
console.log(result);
You can use .map() and .concat() to get the desired result:
let data = [{
cells: [
{ id: "1", cellType: 3, widget: { id: 1, description: "myDesc"} },
{ id: "1", cellType: 4, widget: { id: 2, description: "myDesc2"} }
]}, {
cells: [
{ id: "3", cellType: 5, widget: { id: 3, description: "myDesc3"} }
]
}];
let result = [].concat(...data.map(({cells}) => cells.map(({widget}) => widget)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

content[i] is undefined when push into array in angularjs

I have json data like below
var data = [{
id: 1,
name: 'mobile',
parentid: 0,
limit:3
}, {
id: 2,
name: 'samsung',
parentid: 1
}, {
id: 3,
name: 'moto',
parentid: 1
}, {
id: 4,
name: 'redmi',
parentid: 1
}, {
id: 5,
name: 'honor',
parentid: 1
}, {
id: 6,
name: 'tv',
parentid: 0,
limit:3
}, {
id: 7,
name: 'tv1',
parentid: 6
}, {
id: 8,
name: 'tv2',
parentid: 6
}, {
id: 9,
name: 'tv3',
parentid: 6
}, {
id: 10,
name: 'tv4',
parentid: 6
}, {
id: 11,
name: 'tv5',
parentid: 6
}];
i took parentid zero from json and made a loop in ng-repeat
$scope.cat = categories.filter(function(category) {
return category && category.parentId === 0
});
i have created ng-repeat for this category.whgen i click category all corresponding sub categories pushed into array but when i tried to push my data into array i am getting an error
$scope.category_modal = function(id)
{
for(var i =0;i<=$scope.content.length;i++)
{
if($scope.content[i].parentId === id && typeof $scope.content[i] != 'undefined')
{
$scope.newcat.push($scope.content[i]);
}
}
}
my view page looks like below
<div ng-repeat="item in cat">
{{item.name}}
<button ng-click="category_modal(item.parentid)"></button>
</div>
here i got an error as $scope.content[i] is undefined
Are you getting values in $scope.content?
If yes , check have you declared properly
$scope.content = [];

Reorder array of objects based on attribute

I have an array of objects, each with an 'id' and a 'name'. I'm retrieving an 'id' from the server and need to reorder the array starting from this id.
Example code:
var myList = [
{
id: 0,
name: 'Joe'
},
{
id: 1,
name: 'Sally'
},
{
id: 2,
name: 'Chris'
},
{
id: 3,
name: 'Tiffany'
},
{
id: 4,
name: 'Kerry'
}
];
Given an 'id' of 2, how can I reorder the array so my output is as follows:
var newList = [
{
id: 2,
name: 'Chris'
},
{
id: 3,
name: 'Tiffany'
},
{
id: 4,
name: 'Kerry'
},
{
id: 0,
name: 'Joe'
},
{
id: 1,
name: 'Sally'
}
];
Try this:
function orderList(list, id){
return list.slice(id).concat(list.slice(0,id));
}
Link to demo
You could slice the array at given index and return a new array using spread syntax.
const myList = [{id:0,name:'Joe'},{id:1,name:'Sally'},{id:2,name:'Chris'},{id:3,name:'Tiffany'},{id:4,name:'Kerry'}];
const slice = (arr, num) => [...arr.slice(num), ...arr.slice(0, num)];
console.log(slice(myList, 2));
myList.sort(function(a,b){
return a.id>2===b.id>2?a.id-b.id:b.id-a.id;
});
newList=myList;
http://jsbin.com/kenobunali/edit?console
You could splice the wanted part and use splice to insert it at the end of the array.
var myList = [{ id: 0, name: 'Joe' }, { id: 1, name: 'Sally' }, { id: 2, name: 'Chris' }, { id: 3, name: 'Tiffany' }, { id: 4, name: 'Kerry' }],
id = 2;
myList.splice(myList.length, 0, myList.splice(0, myList.findIndex(o => o.id === id)));
console.log(myList);
using es6 spread syntax
var myList = [{ id: 0, name: 'Joe' }, { id: 1, name: 'Sally' }, { id: 2, name: 'Chris' }, { id: 3, name: 'Tiffany' }, { id: 4, name: 'Kerry' }],
id = 2;
var index = myList.findIndex(o => o.id == id);
var arr = myList.splice(0, index);
var result = [...myList, ...arr];
console.log(result);

Merge two arrays into one with push()

I've got follow code:
list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
list1.push(list2);
I expect follow result:
list1:
0: Object (Zurich)
1: Object (London)
3: Object (New York)
4: Object (Dummy)
5: Object (Dummy2)
But I get this one:
list1:
0: Object (Zurich)
1: Object (London)
2: Object (New York)
3: Object (Items)
0: Object (Dummy)
1: Object (Dummy2)
How can I get my expectet result?
Thanks and cheers.
Beside Array#concat, you could use Array#push.apply for it
var list1 = { Items: [{ ID: 1, Name: "Zurich" }, { ID: 2, Name: "London" }, { ID: 3, Name: "New York" }] },
list2 = { Items: [{ ID: -1, Name: "Dummy" }, { ID: 0, Name: "Dummy2" }] };
[].push.apply(list1.Items, list2.Items);
console.log(list1);
The question was how to do this with push() not concat():
for (var i = 0; i < list2.Items.length; i++) {
list1.Items.push(list2.Items[i]);
}
Use the spread operator:
list1.Items.push(...list2.Items)
Spread is an ES2015 feature. Your target browsers or runtime may not support it yet, so check the compatibility table (or use a transpiler like babel).
list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
list1.Items = list1.Items.concat(list2.Items);
console.log(list1);
try with:
list2.items.forEach(function (item) {
list1.items.push(item)
})
You need to loop through each items in list2 and then fetch them to push into list1.. Below is the snippet using $.each
var list1 = {
Items: [
{
ID: 1,
Name: "Zurich"
},
{
ID: 2,
Name: "London"
}, {
ID: 3,
Name: "New York"
}
]
};
var list2 = {
Items: [
{
ID: -1,
Name: "Dummy"
},
{
ID: 0,
Name: "Dummy2"
}
]
};
$(list2.Items).each(function(k,v){
list1.Items.push(v);
})
console.log(list1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Manually change data items in datasource

I have the following datasource with data set to an array.
var dataArray = [
{ Id: 1, Name: "RootA", ParentId: null },
{ Id: 2, Name: "ChildA", ParentId: 1 },
{ Id: 3, Name: "RootB", ParentId: null },
{ Id: 4, Name: "ChildB", ParentId: 3 },
{ Id: 5, Name: "RootC", ParentId: null }
];
var treeListDataSource = new kendo.data.TreeListDataSource({
data: dataArray,
schema: {
model: {
id: "Id",
fields: {
parentId: { field: "ParentId", type: "number", nullable: true },
Id: { field: "Id", type: "number" }
}
}
}
});
This works.
Now I want to change the items in dataArray to:
var newData = [
{ Id: 6, Name: "RootD", ParentId: null },
{ Id: 7, Name: "ChildD", ParentId: 6 },
{ Id: 8, Name: "RootE", ParentId: null }
];
I tried:
Just setting it: dataArray = newData;
Setting via the data() method in the kendo datasource: treeListDataSource.data(newData)
But the grid doesn't display the new values. Instead is just says "no records".
Here's a demo.
I think there is some kind of bug that parentId field won't look up to modified field ParentId after initiation.
You can solve this with create the whole datasource definition again.
Your code should be like this:
<kendo-treelist id="treelist" k-options="treelistOptions"></kendo-treelist>
$scope.change = function() {
var treelist = $("#treelist").data().kendoTreeList;
var newData = [
{ Id: 6, Name: "RootD", ParentId: null },
{ Id: 7, Name: "ChildD", ParentId: 6 },
{ Id: 8, Name: "RootE", ParentId: null }
];
var newDs = new kendo.data.TreeListDataSource({
data: newData,
schema: {
model: {
id: "Id",
fields: {
parentId: { field: "ParentId", nullable: true },
Id: { field: "Id", type: "number" }
}
}
}
});
treelist.setDataSource(newDs);
};
I managed to get it working using the transport API. http://dojo.telerik.com/OBUSU/4
var treeListDataSource = new kendo.data.TreeListDataSource({
transport: {
read: function (options) {
var data = dataArray;
options.success(data);
}
},
...
});
function change() {
var newData = [
{ Id: 6, Name: "RootD", ParentId: null },
{ Id: 7, Name: "ChildD", ParentId: 6 },
{ Id: 8, Name: "RootE", ParentId: null }
];
dataArray = newData;
treeListDataSource.read();
};

Categories

Resources