nested foreach with knockout binding? - javascript

My JSON object and observablarray are like :
self.myComplexsObject= ko.observableArray([{
"TupleArray": [{
"OptInfo": {
"Version": "B",
"Name": "csk_profile"
},
"Parameter": [{
"Value": "1",
"Name":"min SampleCopunt"
}]
},
{
"OptInfo": {
"Version": "A",
"Name": "Dml_profile"
},
"Parameter": [{
"Value": "2",
"Name":"min SampleCopunt"
}]
}]
}]);
and I want to access to Name and Version like below: But its not working Could you please help me??
<div data-bind='template: { foreach: myComplexsObject,
beforeRemove: hideElement,
afterAdd: showElement }'>
<div data-bind="foreach: OptInfo">
<div data-bind='attr: { "class": "complexObject" + Name,"title":Name},
text: Version'></div>
</div>
</div>

You can't access "OptInfo" this way because of the structure of your JSON. You are passing an array of one object to the observableArray. Here is the structure of this object:
{
"TupleArray":[
{
"OptInfo":{
"Version":"B",
"Name":"csk_profile"
},
"Parameter":[
{
"Value":"1",
"Name":"min SampleCopunt"
}
]
},
{
"OptInfo":{
"Version":"A",
"Name":"Dml_profile"
},
"Parameter":[
{
"Value":"2",
"Name":"min SampleCopunt"
}
]
}
]
}
So, this object, which becomes the context in your for each loop does not have a "OptInfo" property. The object only contains an array of two objects ("TupleArray").

Related

how to make nested array objects in javascript in a key value pair format

array data=[
{
"id":1,
"name":"john",
"income":22000,
"expenses":15000
},
{
"id":2,
"name":"kiran",
"income":27000,
"expenses":13000
},
{
"id":1,
"name":"john",
"income":35000,
"expenses":24000
}
]
i want to make a new array set in following format which is in a key value pair. ie result set.
can you please explain the best method. ? how to achive using foreach.?
tried using foreach method by looping each element. but cant get the desired output format
var result= [ {
"name": "john",
"series": [
{
"name": "income",
"value": 22000
},
{
"name": "expenses",
"value": 15000
},
]
},
{
"name": "kiran",
"series": [
{
"name": "income",
"value": 27000
},
{
"name": "expenses",
"value": 13000
},
]
}]
// Your array
const result = [
{
name: "john",
series: [
{
name: "income",
value: 22000,
},
{
name: "expenses",
value: 15000,
},
],
},
{
name: "kiran",
series: [
{
name: "income",
value: 27000,
},
{
name: "expenses",
value: 13000,
},
],
},
];
// What is .map function?
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
// Output
// map return a new function.
// it's a loop method but more equipped
result.map((item, index) => {
const seriesKeyValues = {};
// forEach is too, it's a loop method.
// but not have a return value,
// just loops and give you item on each loop
item.series.forEach(serie => {
//seriesKeyValues is a object.
// different between seriesKeyValues.serie.name
// it's a bracket notation
// look this documentation
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names
seriesKeyValues[serie.name] = serie.value;
});
// return new Object
// ... is 'spread syntax' basically combine objects
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#spread_properties
// spread syntax is a new way.
// old way is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
return {
id: index,
name: item.name,
...seriesKeyValues,
};
});
I hope it will help :). if you don't understand any lines of code, i can explain

cannot update an array of elements via a 2d iteration

I have two arrays of object, the first array (printerChart, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
},
....
]
The second array (items, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "hp"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do is to iterate via the second array and, if the part of the name of an item (i.e. DT8) is included in an element of the array 'compatibility' of the first array, I would like to include a new properties to it from the element of the first array: printerBrand. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
items.forEach((item) => {
printerChart.forEach((printer) => {
if (printer.compatibilty.some(compatibleElem => (
item.name.includes(compatibleElem)))) {
item.printerBrand = printer.printerBrand;
} else {
item.printerBrand = '';
}
});
});
What am I doing wrong?
You do
items.items.forEach(...)
Shouldn't you be doing
items.forEach(...)
?
I suggest to initialize item.printerBrand with an empty string and use a nested approach of some for getting a brand and to exit the loops, if found.
This prevents to get an empty string even if there is a brand to assign.
items.forEach((item) => {
item.printerBrand = '';
printerChart.some(printer => {
if (printer.compatibilty.some(compatibleElem => item.name.includes(compatibleElem))) {
item.printerBrand = printer.printerBrand;
return true;
}
});
});

Vue.js : passing item as parameter to computed prop in v-for, returning child array sorted ?

Have been googling around for quite a while to figure out how to do this..
I have a list of "Intents", which each of them got a list of "Entities", presented in a nested v-for.
Intents are already computed, but i need to also sort the "Entities" list on the fly, so therefore i thought that making that list also computed..
Error :
**TypeError: _vm.entityList is not a function**
This is my current approach :
< script >
import uniq from 'lodash/uniq'
import orderby from 'lodash/orderby'
import Util from "#/components/util.js"
export default {
data() {
return {
// ....
}
},
computed: {
nluData() {
return orderby(this.$store.getters.nlujson.filter(item => {
return item.intent.toLowerCase() === this.selectedIntent
}), ['intent', 'text'], ['asc', 'asc'])
},
entityList(item) {
return orderby(item.entities, ['entity', 'value'], ['asc', 'asc'])
},
},
created() {
this.$store.dispatch('getNluJson')
},
methods: {
// ......
}
</script>
// parent structure
<div v-for="(item, key, index) in nluData">
// displaying nluData content through item.mydata // child structure
<div v-for="ent in entityList(item)">
// displaying entities data through computed prop. // item.entities is the array
</div>
</div>
{
"id": "J4a9dGEBFtvEmO3Beq31",
"text": "This is Intent 1",
"intent": "shelf_life",
"entities": [
{
"start": "33",
"end": "44",
"value": "fridge",
"entity": "ingredient_placement"
},
{
"start": "10",
"end": "20",
"value": "duration",
"entity": "shelf_life"
},
{
"start": "25",
"end": "30",
"value": "spareribs",
"entity": "ingredient"
}
]
},
You can pass parameters to a computed property with an anonymous function like so:
computed: {
entityList() {
return (item) =>
orderby(item.entities, ['entity', 'value'], ['asc', 'asc']);
},
},
A computed property don't get any params. In your case, the prop entityList() must be a method :
methods : {
entityList(item) {
return orderby(item.entities, ['entity', 'value'], ['asc', 'asc'])
},
},
https://v2.vuejs.org/v2/guide/computed.html

How to iterate through deeply nested objects inside of a JSON?

I know there are plenty of questions about iterating through JSON objects but I haven't found one that quite relates to my exact problem. This is the JSON that I'm trying to iterate through:
psinsights = {
"kind": "pagespeedonline#result",
"id": "/speed/pagespeed",
"responseCode": 200,
"title": "PageSpeed Home",
"score": 90,
"pageStats": {
"numberResources": 22,
"numberHosts": 7,
"totalRequestBytes": "2761",
"numberStaticResources": 16,
"htmlResponseBytes": "91981",
"cssResponseBytes": "37728",
"imageResponseBytes": "13909",
"javascriptResponseBytes": "247214",
"otherResponseBytes": "8804",
"numberJsResources": 6,
"numberCssResources": 2
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidBadRequests": {
"localizedRuleName": "Avoid bad requests",
"ruleImpact": 0.0
},
"MinifyJavaScript": {
"localizedRuleName": "Minify JavaScript",
"ruleImpact": 0.1417,
"urlBlocks": [
{
"header": {
"format": "Minifying the following JavaScript resources could reduce their size by $1 ($2% reduction).",
"args": [
{
"type": "BYTES",
"value": "1.3KiB"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
},
"urls": [
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://code.google.com/js/codesite_tail.pack.04102009.js"
},
{
"type": "BYTES",
"value": "717B"
},
{
"type": "INT_LITERAL",
"value": "1"
}
]
}
},
{
"result": {
"format": "Minifying $1 could save $2 ($3% reduction).",
"args": [
{
"type": "URL",
"value": "http://www.gmodules.com/ig/proxy?url\u003dhttp%3A%2F%2Fjqueryjs.googlecode.com%2Ffiles%2Fjquery-1.2.6.min.js"
},
{
"type": "BYTES",
"value": "258B"
},
{
"type": "INT_LITERAL",
"value": "0"
}
]
}
}
]
}
]
},
"SpriteImages": {
"localizedRuleName": "Combine images into CSS sprites",
"ruleImpact": 0.0
}
}
},
"version": {
"major": 1,
"minor": 11
}
};
Now, I'm trying to write a function that iterates through all of the ruleResults objects and returns an array of the localizedRuleName properties. According to the JSON, ruleResults has three member objects (AvoidBadRequests, MinifyJavaScript, and SpriteImages). Each of these has a localizedRuleName property I'm trying to access, but when I print out my array, it's blank. Here's how I've written my function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
}
return ruleArray;
}
console.log(ruleList(psinsights));
Can you guys help me get on the right track? I used basically this same method to iterate through the pageStats of the JSON and it worked perfectly. I'm not sure why I can't get it to work with these deeper nested objects and properties.
your problem is not your iteration, but your undefined variable "counter".
Instead of using a counter can use the "push" function:
function ruleList(results) {
var ruleArray = [];
for(var ruleName in results.formattedResults.ruleResults){
ruleArray.push(results.formattedResults.ruleResults[ruleName].localizedRuleName);
}
return ruleArray;
}
fiddle: https://jsfiddle.net/fo9h56gh/
Hope this helps.
you're probably getting a javascript error since counter is not defined. you can try this:
function ruleList(results) {
var ruleArray = [];
var counter = 0;
for(var ruleName in results.formattedResults.ruleResults){
ruleArray[counter] = results.formattedResults.ruleResults[ruleName].localizedRuleName;
counter++;
}
return ruleArray;
}

How to get JSON sub array data from array with equal option and value with Mustache.js?

I am trying to work with Mustache.js that is really helping.
I am stuck on getting array with specific option and value.
My JSON is looking like that:
{
"departments": [
{
"department": [
{
"id": 114,
"deptName": "Department 1",
"category": [
{
"id": 127,
"catName": "Category Name",
"subCategory": []
},
{
"id": 115,
"catName": "Category Name",
"subCategory": []
}
]
}
]
},
{
"department": [
{
"id": 123,
"deptName": "Department 2",
"category": [
{
"id": 126,
"catName": "Category Name",
"subCategory": []
},
{
"id": 124,
"catName": "Category Name",
"subCategory": []
}
]
}
]
}
]
}
To get main department names it is easy as:
JS:
$.ajax({
url: 'link_to_json',
dataType: 'json',
success: function(data) {
var template = $('#pageHomeTpl').html();
var html = Mustache.to_html(template, data);
$('#category-list').html(html);
}
});
HTML:
<ul id="category-list">
<script id="pageHomeTpl" type="text/template">
{{#departments}}
{{#department}}
<li>{{deptName}}</li>
{{/department}}
{{/departments}}
</script>
</ul>
But now I need to somehow get categories ("category:") from department with specific ID, for example "id": 114.
Any help, please.
You can try in these lines, with jQuery map() and grep()
console.log(JSON.stringify(data));
var filtereddata = {"departments" : []};
var filtereddept= {};
filtereddept.department= $.map(data.departments, function(alldept,indx){
return $.grep(alldept.department, function(deptobj,indx){
return deptobj.id==114;
});
});
filtereddata.departments[0]=filtereddept;
console.log(JSON.stringify(filtereddata));
The template to iterate the category of departments:
<script id="pageHomeTpl" type="text/template">
{{#departments}}
{{#department}}
<li>{{deptName}}</li>
{{#category}}
<ul>
<li>{{catName}}</li>
</ul>
{{/category}}
{{/department}}
{{/departments}}
</script>
I don't test it but it seems to be work...
...
success: function(data) {
var template = $('#pageHomeTpl').html();
var item = data.departments
for(key in item){
if(key == 'id' && item[key] == 114 ){
var html = Mustache.to_html(template, item);
}
}
$('#category-list').html(html);
}
...
with FOR .. IN statement you can cycle in your object or array take look at this link
js_loop_for_in

Categories

Resources