associative array : cannot set property of undefined - javascript

I have to retrieve the data from a JSON file then assign it to an array. But I am getting an error
"Cannot set property 'ref' of undefined".
Converting JSON to associative arrays or objects.
var items2=[[]];
$.getJSON("results.json", function( data ) {
$.each( data, function( key, val ) {
if(key=="items")
{
$.each(val,function(keyScd,valScd)
{
$.each(valScd,function(keyTrd,valTrd)
{
var ref=JSON.stringify(valTrd.ref).slice(1,-1);
var prix=JSON.stringify(valTrd.prix).slice(1,-1);
var taille=JSON.stringify(valTrd.taille).slice(1,-1);
items2[keyScd][keyTrd]["ref"]=ref;
items2[keyScd][keyTrd]["prix"]=prix;
items2[keyScd][keyTrd]["taille"]=taille;
});
});
}
else
{
items2[key]=val;
}
});
});
and here is my JSON
{
"items":[
[
{
"ref":"cpe-zfmmpx23",
"nomc":"1",
"description":"yellow sofa",
"dispo":"1",
"prix":"300",
"taille":"standard",
"couleur":"jaune"
},
{
"ref":"cpe-zfmmpx23",
"nomc":"2",
"description":"yellow sofa",
"dispo":"1",
"prix":"400",
"taille":"0.5mH,2mW",
"couleur":"red"
}
]
],
"buildNumber":"fa36b5153f33240a111e6dc336a70"
}

You should just be able to map the elements. Is this what you are after?
var temp = `{"items":[[{"ref":"cpe-zfmmpx23","nomc":"1","description":"yellow sofa","dispo":"1","prix":"300","taille":"standard","couleur":"jaune"},{"ref":"cpe-zfmmpx23","nomc":"2","description":"yellow sofa","dispo":"1","prix":"400","taille":"0.5mH,2mW","couleur":"red"}]],"buildNumber":"fa36b5153f33240a111e6dc336a70"}
`;
var data = JSON.parse(temp);
var items2;
if (data.items) {
items2 = $.map(data.items, function(items) {
return $.map(items, function(item) {
return {
ref: item.ref.slice(1, -1),
prix: item.prix.slice(1, -1),
taille: item.taille.slice(1, -1)
};
});
});
}
console.log(items2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Here is another way to do it, no need for jquery there :
const json = '{"items":[[{"ref":"cpe-zfmmpx23","nomc":"1","description":"yellow sofa","dispo":"1","prix":"300","taille":"standard","couleur":"jaune"},{"ref":"cpe-zfmmpx23","nomc":"2","description":"yellow sofa","dispo":"1","prix":"400","taille":"0.5mH,2mW","couleur":"red"}]],"buildNumber":"fa36b5153f33240a111e6dc336a70"}';
const newJson = JSON.parse(json);
(newJson.items).forEach((data) => {
data.forEach((newData) => {
console.log(newData.ref)
});
});

Related

Put object in nested object

Ik have to object and I want to combine those together the right way. I use this code to get them together:
return { record, voorraad: resultsr.filter(x => x != null) }
the output of this will be
{
record:{
_id:"5e8c226e62e43e41b59fe3d3",
naam:"Dames fietsen"
},
voorraad:[
{
_id:"5e8cc9e059fcf75489ebac84",
categorie:"5e8c226e62e43e41b59fe3d3",
status:1
}
]
}
But I like to have it this way
{
record:{
_id:"5e8c226e62e43e41b59fe3d3",
naam:"Dames fietsen",
voorraad:[
{
_id:"5e8cc9e059fcf75489ebac84",
categorie:"5e8c226e62e43e41b59fe3d3",
status:1
}
]
}
}
Who can help me?
this way ?
var data = {
"record":{
"_id":"5e8c226e62e43e41b59fe3d3",
"naam":"Dames fietsen"
},
"voorraad":[
{
"_id":"5e8cc9e059fcf75489ebac84",
"categorie":"5e8c226e62e43e41b59fe3d3",
"status":1
}
]
}
data.record.voorraad = data.voorraad
delete data.voorraad
console.log( JSON.stringify( data, 0 ,2))
uses destructuring:
const data = {
record:{
_id:"5e8c226e62e43e41b59fe3d3",
naam:"Dames fietsen"
},
voorraad:[
{
_id:"5e8cc9e059fcf75489ebac84",
categorie:"5e8c226e62e43e41b59fe3d3",
status:1
}
]
};
const { record, voorraad } = data;
const test = { ...record, voorraad: voorraad.filter(x => x != null) }
console.log(test);
// you have these
const record = {"_id":"5e8c226e62e43e41b59fe3d3", "naam":"Dames fietsen"};
const results = [
{
"_id":"5e8cc9e059fcf75489ebac84",
"categorie":"5e8c226e62e43e41b59fe3d3",
"status":1
}
];
// so just do this
record.voorraad = results.filter(x => x);
const returnValue = { record };
// and returnValue is what you want
console.log(returnValue);

Better way to map a deep object to new object

This code works for converting the JSON to an object where each name object turns into the key for either its value, or if it instead has its own element object breaks that out and does the same to its contents.
Is there a better way to do this that would also allow for more extensiblity of the JSON schema?
Is there a way I can get it all down to a simpler function that I can pass the first element and have it convert it down to whatever depth the schema goes?
const fs = require('fs');
{
let scheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version='1.0'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root;
let depth = 0;
var compiled = {
[scheme.ele.name]: scheme.ele.ele.map(function(i) {
if (typeof i.ele != 'undefined') {
return {
[i.name]: i.ele.map(function(k) {
if (typeof k.ele != 'undefined') {
return {
[k.name]: k.ele.map(function(p) {
if (typeof p.ele != 'undefined') {
return {
[p.name]: p.ele
};
} else {
return {
[p.name]: p.value
};
}
})
};
} else {
return {
[k.name]: k.value
};
}
})
};
} else {
return {
[i.name]: i.value
};
}
})
};
}
console.log(JSON.stringify(compiled, 0, 2));
I should add, this is intended to eventually also apply validation and grab real data when it gets to the string objects.
The output looks like this:
{
"REPORT": [
{
"SEGMENT0": [
{
"NUMBER1": ""
},
{
"NUMBER2": ""
}
]
},
{
"SEGMENT1": [
{
"RECORD1": [
{
"NUMBER1": ""
},
{
"NUMBER2": ""
}
]
}
]
},
{
"SEGMENT2": []
},
{
"SEGMENT3": []
},
{
"SEGMENT4": []
},
{
"SEGMENT5": []
}
]
}
You could destructure the object, get name, ele and value and return a new object with name as key and either an array by mapping the objects of ele or the value.
const
getData = ({ name, ele, value }) => ({
[name]: Array.isArray(ele)
? ele.map(getData)
: value
});
var scheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version=\'1.0\'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root,
result = getData(scheme.ele);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina's answer is cleaner but this looks a bit more like your code so I figured I'd post it anyway.
let scheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version=\'1.0 \'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":""},{"name":"NUMBER2","value":"1"}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":"2"},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root;
let newScheme = JSON.parse('{"$schema":{"root":{"name":"THINGY","dtd":{"name":"DOCTYPE","value":"something.dtd","commentBefore":["?xml version=\'1.0 \'?","Version NULL"]},"ele":{"name":"REPORT","ele":[{"name":"SEGMENT0","ele":[{"name":"NUMBER1","value":"1"},{"name":"NUMBER2","value":"3"}]},{"name":"SEGMENT1","ele":[{"name":"RECORD1","ele":[{"name":"NUMBER1","value":"4"},{"name":"NUMBER2","value":""}]}]},{"name":"SEGMENT2","ele":[]},{"name":"SEGMENT3","ele":[]},{"name":"SEGMENT4","ele":[]},{"name":"SEGMENT5","ele":[]}]}}}}').$schema.root;
//Yay, recursion!
function mapObj(a, o = {}) {
let array = o[a.name] || [];
for (let i = 0; i < a.ele.length; i++) {
let b = a.ele[i];
array[i] = b.ele ?
mapObj(b, array[i]) : {
[b.name]: b.value
};
}
o[a.name] = array;
return o;
}
let obj = mapObj(scheme.ele);
console.log(obj);
console.log(mapObj(newScheme.ele, obj));

Add elements from array to object to format fusionchart data

I want to format the data of my fusion chart based on scope variable.
I have a function which gets dates and stock values assigned to this dates.
So I have 2 arrays:
dates = [2017-04-28, 2017-04-27, 2017-04-26, 2017-04-25]
stockValues = [150.25, 147.7, 146.56, 146.49]
What I want to do is to create a new object which looks like this:
data: [{
"label": "2017-04-28",
"value": "150.25"
},
{
"label": "2017-04-27",
"value": "147.7"
},
... //and so on
]
I managed to come up with following code:
$scope.getStockData = function(stockID) {
$http.get('/stock', {
params : {
stockID : encodeURI(stockID)
}
}).then(function(response) {
$scope.stock = response.data;
var data={};
$scope.data={};
angular.forEach(response.data.dates,function(value){
data["label"] = value;
})
angular.forEach(response.data.stockValues,function(value){
data["value"] = value;
})
$scope.data = data;
}, function(response) {
$scope.showError = true;
}).finally(function() {
});
};
The problem is that this solution creates object which looks like this:
{"label":"2017-04-25","value":"146.49"}
So it takes only the last values from array.
How can I make my object look the way I want it to?
Example:
const dates = ['2017-04-28', '2017-04-27', '2017-04-26', '2017-04-25']
const stockValues = ['150.25', '147.7', '146.56', '146.49']
const r = dates.map((d, i) => Object.assign({
label: d,
value: stockValues[i]
}))
console.log(JSON.stringify(r, null, 2))
Try this, you must initialize an array, and the push at the right location.
$scope.getStockData = function(stockID) {
$http.get('/stock', {
params : {
stockID : encodeURI(stockID)
}
}).then(function(response) {
$scope.stock = response.data;
var data=[];
$scope.data=[];
angular.forEach(response.data.dates,function(value, i){
data[i]["label"] = value;
})
angular.forEach(response.data.stockValues,function(value, i){
data[i]["value"] = value;
})
$scope.data = data;
}, function(response) {
$scope.showError = true;
}).finally(function() {
});
};

extract fields in javascript

I have a dictionary where i want to extract some fields with their keys. So what i want is call a function where i pass this dictionary and the keys.
var posts = {
"code":"ok",
"data":[
{
"id":1,
"username":"example1",
"data":
{
"id":4,
"name":"fran"
},
},
{
"id":2,
"username":"example2",
"data":
{
"id":5,
"name":"manuel"
}
}
]
};
So I would like to have a new dictionary where i have the nested value as a simple dictionary value.
[{
"id":1,
"username":"example1",
"name":"fran"
},
"id":2,
"username":"example2",
"name":"manuel"
}}
function dict(obj)
{
var list = Object.assign({},obj).data;
list.forEach((e,i,a) => {
e.name = e.data.name;
delete e.data;
});
return list;
}
that's how you dictionary function should look
I have tried this one. I think i have problem because i am creating a dictionary when node is "name" in the iteration. So i want to confirm if it's OK or there is any another way to do this.
var list = [];
var dict = {};
function iterate(obj, stack) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '.' + property);
} else {
console.log(property + " " + obj[property]);
dict[property] = obj[property];
if(property=="name"){
list.push(dict);
dict ={};
}
}
}
}
return list;
}
var simplified = iterate(posts.data, '');
console.log(simplified);

Creating json in specific format using javascript

I have a complex javascript code which when simplified is as below..
function getjson1() {
return {
'json1': {
id: 'jsonid1'
}
};
}
function getjson2() {
return {
'json2': {
id: 'jsonid2'
}
};
}
myjson = [];
myjson.push(getjson1());
myjson.push(getjson2());
function finaljson() {
return {
'json': myjson
};
}
console.log(JSON.stringify(finaljson()));
Now the result of this code is
{"json":[{"json1":{"id":"jsonid1"}},{"json2":{"id":"jsonid2"}}]}
Now this code I need to change such that I can get rid of the array and can traverse the json object like.. json.json1.id, etc..
One example could be as below..
{"json":{"json1":{"id":"jsonid1"},"json2":{"id":"jsonid2"}}}
Any help is sincerely appreciated.
Thanks
Well if you don't want an array, don't use one. First, a jQuery-based solution:
myjson = {};
myjson = $.extend(myjson, getjson1());
myjson = $.extend(myjson, getjson2());
In native JavaScript, you can use the following function:
function extend (target, source) {
Object.keys(source).map(function (prop) {
target[prop] = source[prop];
});
return target;
};
This way, the first code becomes this:
myjson = {};
myjson = extend(myjson, getjson1());
myjson = extend(myjson, getjson2());
You are pushing it to an array so you are getting an array.
use this simple add function to push it in an object in the format you want.
First key in the function returns will be the key in the end object.
function getjson1() {
return {
'json1': {
id: 'jsonid1'
}
};
}
function getjson2() {
return {
'json2': {
id: 'jsonid2'
}
};
}
function add(obj, toadd) {
for(var key in toadd) {
if(toadd.hasOwnProperty(key)) {
obj[key] = toadd[key];
break;
}
}
return obj;
}
myjson = {};
add(myjson,getjson1());
add(myjson,getjson2());
function finaljson() {
return {
'json': myjson
};
}
console.log(JSON.stringify(finaljson()));

Categories

Resources