How can i build this json format in javascript? - javascript

I have this json where the values will be passed dynamically in javascript,
{
"User": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"memNum": "70000211981",
"orderslist": [
{
"orderid": "5119534",
"ordersource": "ONLINE",
"transactiondttm": "2014-01-09"
},
{
"orderid": "5119534",
"ordersource": "STORE",
"transactiondttm": "2014-01-09"
}
]
}
}
and i tried using this function to build the json but it doesnt seem to work,
function addOrder(req, orderId, orderSource, transactiondtm) {
req.User.orderslist.orderid.push(orderId);
req.User.orderslist.ordersource.push(orderSource);
req.User.orderslist.transactiondtm.push(transactiondtm);
}
Any suggestion..

The elements of orderslist are objects, not arrays, so you can't push onto them. You have to build them as objects, and then push that onto the orderslist array.
function addOrder(req, orderId, orderSource, transactiondtm) {
req.User.orderslist.push({ orderid: orderId,
ordersource: orderSource,
transactiondtm: transactiondtm });
}

Something like this should work.
function addOrder(req, orderId, orderSource, transactiondtm) {
req.User.orderslist.push({
"orderid": orderId,
"ordersource": orderSource,
"transactiondtm": transactiondtm
});
}

Javascript objects can be acessed like an array.
That way you can create dinamic members.
user = {"orderList":[]};
for(var i = 0; i<5; i++){
user.orderList[i] = {};
user.orderList[i]["orderId"] = i;
user.orderList[i]["orderSource"] = "STORE";
}
alert(user.orderList[0].orderSource);
//Shows "STORE"
you can see the code working here http://jsfiddle.net/wmgE6/

Related

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Push object to a JSON file subarray/object

Both JS or Node.js solution are welcome
I have a json file with following structure (I have remove some unnecessary part)
{
"post": {
"sample_post": {
"slug": "/sample"
}
}
}
And I want to push a new object array like "sample_post" and someone suggest to change this array to
{
"post": [{
"sample_post": {
"slug": "/sample"
}
}]
}
to use push but I got error like data.push is not a function since I use jquery to get the external json I don't know if this cause error
based on your code :
var data = {
"post": {
"sample_post": {
"slug": "/sample"
}
}
}
you have to use a temporary variable to store the new array :
var _tmp = []
_tmp.push(data.post)
and overright your initial data
data.post = _tmp
I m not sure what you want is just :
var test = {
"post": {
"sample_post": {
"slug": "/sample"
}
}
};
test.post = [test.post];
If you prepare object like shown below,
var obj = {
"post": [{
"sample_post": {
"slug": "/sample"
}
}]
}
then you should be adding the objects into "post" array, in either of the ways.
obj.post.push({"key": "value"})
or
obj["post"].push({"key": "value"})
To use push function, the object should be of type Array. But in your case its a json object. So you first need to make it Array either by initializing it by blank array. ie data.post = [] or directly with array with required elements. After this you can use push in post.push().
Hope this help!

How to get data from json array using names instead of index with jquery

I've been trying to get json data with jquery using names but without succeed, only works with object index, this is my code:
var json = [
{
"idiom":[
{
"nombre":"español",
"id":1
},
{
"nombre":"ingles",
"id":2
}
]
}
];
console.log(json)
$.each( json[0], function( key, data ) {
$.each(data, function(index, indata) {
console.log(indata.nombre);
});
});
console.log('-------');
$.each( json.idiom, function( key, data ) {
$.each(data, function(index, indata) {
console.log(indata.nombre);
});
});
If I try to access with json.idiom isntead of json[0] the code doesn't work
Here is a fiddle: https://jsfiddle.net/wm0de41h/
You're having to access json[0] because it's an array with a single item in it. If you want to access json.idiom you'll need to restructure your object to:
var json = {
"idioms":[
{
"nombre":"español",
"id":1
},
{
"nombre":"ingles",
"id":2
}
]
};
Notice how there are no square brackets around your json object now. (I also pluralized idioms since it's an array.
Finally, you don't need jquery to iterate this. You can use an Array.forEach().
json.idiom.forEach(function(idiom) {
console.log(idiom.nombre);
});
A JSON object is defined using curly braces {}, not brackets []. Try removing the brackets, which would leave you with this:
var json = {
"idiom":[
{
"nombre":"español",
"id":1
},
{
"nombre":"ingles",
"id":2
}
]
};
See the JavaScript object documentation at MDN.

Restructure JS object to fit binding MVC model

I have a javascript object with nested objects obtained by a plugin saved in a variable called 'json':
// var json:
Object {0: Object, 1: Object}
0: country
countryCapital: Object
ministers: Array[1]
1: country
countryCapital: Object
ministers: Array[3]
// Should be restructured to fit MVC models
World
Country Array [2]
Capital: Object
Minister: Array [1]
Because I'm sending the data using jQuery-ajax to a MVC controller I'm trying to rename/restructure them to bind them to a MVC Model so I can send the whole 'World' object as 1 parameter.
// Controller
[HttpPost]
public void Save(World world)
// Model structure:
World
* Country (list)
1 Capital
* Minister (list)
How do I convert the javascript object to the right structure that fits the Model parameter? Do I need to loop everything or can it be done in a better way?
UPDATE:
json object update, it's a lot of data so I simplified it.
// World
{
"0": { // Country
"ministers":
{
"objects": [
{
"name": "name1"
},
{
"name": "name2"
}
]
},
"countryCapital": {
"name": "...",
}
},
"1": { // Country
"ministers":
{
"objects": [
{
"name": "name1"
},
{
"name": "name2"
}
]
},
"countryCapital": {
"name": "...",
}
}
}
I suppose you're searching for $.map().
At the background it's looping your collection but it much cleaner to use it in your case.
Updated to use your example json. Jsfiddle
var world = {}
for (var countryIteration in originalObject) {
var country = originalObject[countryIteration];
world[countryIteration] = { //you need to this because you need dynamic keys.
capital : country.countryCapital.name,
ministers : country.ministers.objects
}
}
I found a working solution thanks to teo van kot using jQuery map.
var world = {}
$.map(json, function (value, i) {
if (i == "countryCapital") {
world.Capital = value
}
if (i == "ministers") {
world.Minister= value
$.each(value, function (j, minister) {
world.Minister[j].Name = minister.name;
delete minister.name;
});
}
}, world);

Creating a dynamic array

I need to create a dynamic array with a loop.. but I cant seem to get the desired results.
the array I want is:
{
"CategoryName": "somecategoryname",
"Date": "02-17-2012",
"Id": 24,
"ProductToHide": [
{
"IsHide": true,
"ProductId": "someid"
}
],
"ProductsToAdd": [
{
"MealSequence": "S1",
"ProductId": "Someid"
},
{
"MealSequence": "S2",
"ProductId": "Snack_11"
}
],
"UserId": "1"
}
and I am using the following function to add products:
addProduct: function(id){
var tempArr = [];
$.each(this.mCData.ChildCategories, function(i, item){
$.each(item.PList, function(j, jsonPr){
if (jsonPr.TID == id){
addProduct = new mealTypeProduct();
addProduct.data = jsonPr;
tempArr = addProduct.modifyProduct();
}
})
})
// queryStr = {"add" : tempArr};
// this.modificationArray.push(queryStr);
this.modificationArray['add'].push(tempArr);
console.log(this.modificationArray);
}
Its giving me the following error:
this.modificationArray.add.push is not a function
this.modificationArray['add'].push(tempArr);
the initializing is done in the following manner:
var mealType = {
chosenDate: new Date(), tabViewHtml: '',
modificationArray: [], saveArray: [],
}
What am I doing wrong?
This line:
tempArr = addProduct.modifyProduct();
replaces tempArr with a new value, so at the end of the $.each call it will have the value from the last matching product (which may not be an array) rather than being an array of all of them. If that is what you want then that's not a problem.
As to the actual error you quote: what type of thing is this.modificationArray? Does it have a member called add? Does that member have a push() function? Is it initialized properly, or is it left uninitialized? If the latter, then there's your problem: you need to initialize it before you can call push().
UPDATE: If this.modificationArray is initialized as [], as in the new sample code, then it is an array itself; it does not have an add member. The code should say this.modificationArray.push(tempArr).
Alternatively, if you really do want an add member, then this.modificationArray should be initialized as modificationArray : {add:[]}

Categories

Resources