JavaScript wrap some data to json array - javascript

i want to create jSon format from this string value:
hello|world|this|is|javascript || my|name|is|mahdi
in created jSon array from that i can not wrap this string to separator as 2 array by split with ||. my code is work fine but i can not create some array in json after split string with ||.
result my code is:
{
"FILEDS": [
{
"template_id": "123",
"fields_id": "456"
},
{
"item": "hello"
},
{
"item": "world"
},
{
"item": "this"
},
{
"item": "is"
},
{
"item": "javascript "
},
{
"item": " my"
},
{
"item": "name"
},
{
"item": "is"
},
{
"item": "mahdi"
}
]
}
but i want to have this result like with below json format:
{
"FILEDS": [
{
"template_id": "123",
"fields_id": "456"
},
[
{
"item": "hello"
},
{
"item": "world"
},
{
"item": "this"
},
{
"item": "is"
},
{
"item": "javascript "
}
],
[
{
"item": " my"
},
{
"item": "name"
},
{
"item": "is"
},
{
"item": "mahdi"
}
]
]
}
My code is below code and how to create this array in each for for some data to create and wrap to []?
<script type="text/javascript" language="JavaScript">
var data = "hello|world|this|is|javascript || my|name|is|mahdi";
var templates = {
FILEDS: []
};
templates.FILEDS.push({
"template_id": "123",
"fields_id": "456",
});
var split_data = data.split("||");
for (var i = 0; i < split_data.length; i++) {
var fields = split_data[i].split("|");
for (var j = 0; j < fields.length; j++) {
templates.FILEDS.push({
"item": fields[j],
});
}
}
console.log(JSON.stringify(templates));
</script>

Try this;
var split_data = data.split("||");
for (var i = 0; i < split_data.length; i++) {
var sentence = [];
var fields = split_data[i].split("|");
for (var j = 0; j < fields.length; j++) {
sentence.push({
"item": fields[j],
});
}
templates.FILEDS.push(sentence)
}

You'll need a secondary array to hold the data.
var data = "hello|world|this|is|javascript || my|name|is|mahdi";
var templates = {
FILEDS: []
};
templates.FILEDS.push({
"template_id": "123",
"fields_id": "456",
});
var split_data = data.split("||");
for (var i = 0; i < split_data.length; i++) {
var fields = split_data[i].split("|");
var arr = [];
for (var j = 0; j < fields.length; j++) {
arr.push({ "item" : fields[j] });
}
templates.FILEDS.push(arr);
}
console.log(JSON.stringify(templates));
// result" {"FILEDS":[{"template_id":"123","fields_id":"456"},[{"item":"hello"},{"item":"world"},{"item":"this"},{"item":"is"},{"item":"javascript "}],[{"item":" my"},{"item":"name"},{"item":"is"},{"item":"mahdi"}]]}

Yet another variant with Array.map
[].push.apply(templates.FILEDS, data.split("||").map(function(el){
return el.split('|').map(function(item){
return { "item" : item };
})
}));
UPDATE if you want objects like
{ "FILEDS": [
{ "template_id": "123", "fields_id": "456" },
{"items": [
[ "hello", "world", "this", "is", "javascript " ],
[ " my", "name", "is", "mahdi" ]
] }
]}
you can a bit change code above
templates.FILEDS.push({
"item" : data.split("||").map(function(el){
return el.split('|');
})
}
);

Related

javascript: All device data is read into the object

When I write Javascript, I want to read all the data of the device into the object, but only the last one is read.
I would like to ask how I can read all the data in the device into obj, thank you.
let data = [
{
"bind": "82218018295591013",
"account": "admin",
"password": "0000",
"devices": [
{
"ip": "192.168.0.88",
"brand_name": "UNIVIEW",
"name": "UNIVIEW"
}
]
},
{
"bind": "94907378021478863",
"account": "admin",
"password": "0000",
"devices": [
{
"ip": "192.168.0.88",
"brand_name": "UNIVIEW",
"name": "UNIVIEW"
},
{
"ip": "192.168.0.89",
"brand_name": "hisharp",
"name": "hisharp"
}
]
}
]
let obj = {};
function getObj() {
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].devices.length; j++) {
obj.devices = data[i].devices[j];
}
}
return obj;
}
console.log('obj :>> ', obj);
getObj();
You are having a single object for all objects and you store all objects, but the problem is that each time that you store an object, you are overriding the previous one with it.
function getObj(obj) {
obj.devices = [];
for (let i = 0; i < data.length; i++) {
obj.devices.concat(data[i].devices);
}
return obj;
}
and pass obj:
getObj(obj);
console.log('obj :>> ', obj);

Normalize JSON to a custom schema

I have an array of objects with the following format
var arr = [
{
"productId": "123456",
"productName": "Test Product 1",
"description": [
"This is delicious",
"Suitable for vegetarian"
],
"attributes": {
"internalId": "091283"
"category": "Dairy"
},
"order": 1
}
];
And I am trying to map into something like below
[
[{
{
"name": "productId",
"value": "123456"
},
{
"name": "productName",
"value": "Test Product 1"
},
{
"name": "description",
"value": ["This is delicious", "Suitable for vegetarian"]
},
{
"name": "attributes",
"value": {
{
"name": "internalId",
"value": "091283"
},
{
"name": "category",
"value": "Dairy"
}
}
},
{
"name": "order",
"value": 1
}
}]
]
I tried mapping simple properties before going further and now stuck at getting only the last property of each object in the loop.
Suppose I don't know what are the format of incoming data and how can I normalize the JSON object to the format I want?
normalizeJson = (array) => {
for(i = 0; i < array.length; i++){
normalizedJson[i] = {};
Object.keys(array[i]).forEach(key => {
if (array[i][key] && typeof array[i][key] === "object") {
// normalizeJson(obj[key]);
// console.log(key + ' is object');
return;
} else {
o = {};
o["name"] = key;
o["value"] = array[i][key];
normalizedJson[i] = o;
// normalizedJson[i]["name"] = key;
// normalizedJson[i].value = array[i][key];
// console.log(key);
return;
}
});
}
console.log(normalizedJson);
};
Or is there any library I can use in order to achieve this?
Try this
var obj = [
{
productId: "123456",
productName: "Test Product 1",
description: ["This is delicious", "Suitable for vegetarian"],
attributes: {
internalId: "091283",
category: "Dairy",
},
order: 1,
},
];
function normalizeObject(obj) {
var result = [];
if (Array.isArray(obj)) {
for (let i of obj) {
result.push(normalizeObject(i));
}
} else if (typeof obj == "object") {
for (let i of Object.keys(obj)) {
result.push({ name: i, value: normalizeObject(obj[i]) });
}
} else {
return obj;
}
return result;
}
console.log(JSON.stringify(normalizeObject(obj), null, 2));
This looping method called recursion. Which is loop by calling function itself.

Transform array using javascript or angular js

I need to transform below Json array to another array as mentioned below using angularjs/ javascript.
Input Array = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}]
Output Array: [{"Name":"123", "Type1":"24", "Type2":"25"}, {"Name":"124", "Type1":"26", "Type2":"27"}
I would work it out with reduce function I've added some comments for you inside as well:
let inputArray = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];
// and do reduce function on it
inputArray.reduce((prevVal, currVal, index) => {
// first check if there's Name in already
if (prevVal.find(x => x.Name === currVal.Name)) {
// if there's a Name same as current element use new type as a key and add Total
prevVal.find(x => x.Name === currVal.Name)[currVal.Type] = currVal.Total;
} else {
// in case there's no Name then just create object with it
prevVal.push({
Name: currVal.Name,
[currVal.Type]: currVal.Total
});
}
return prevVal;
}, []);
Here's fiddle:
https://jsfiddle.net/pegla/s9hwbth4/
All you have to do is, get the unique objects from the original list based on Name.
var obj = [{
"Name": "123",
"Type": "Type1",
"Total": "24"
},
{
"Name": "123",
"Type": "Type2",
"Total": "25"
},
{
"Name": "124",
"Type": "Type1",
"Total": "26"
},
{
"Name": "124",
"Type": "Type2",
"Total": "27"
}
];
var getIndex = function(list, property, object) {
for (var i = 0; i < list.length; i++) {
if (list[i][property] == object[property]) {
return i;
}
}
return -1;
}
var result = [];
for (var i = 0; i < obj.length; i++) {
/* Call getIndex to return the index of element in the result and add the type name property */
var index = getIndex(result, 'Name', obj[i]);
if (index != -1) {
result[index][obj[i].Type] = obj[i].Total;
} else {
var newObj = {};
newObj.Name = obj[i].Name;
newObj[obj[i].Type] = obj[i].Total;
result.push(newObj);
}
}
console.log(result);
You don't need angularjs to do that. You can do that using simple javascript for block. Please see attached code. Best,
let input = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];
let output = [];
for(let i=0; i<input.length-1;i++){
output.push({
"Name":input[i].Name,
"Type1":input[i].Total,
"Type2":input[i+1].Total,
});
i++;
}
console.log(output);

Updating elemint in JSON updates ALL

I have a JSON object parsed and I am trying to navigate down to SHIPPINGCOMMENTS and update it, but when I do, it updates all cells with that name instead of just the one.
{
"id": 1402846607011,
"status": "unsaved",
"accounts": [
{
"compid": 919759,
"compname": null,
"products": [
{
"BCINUM": "539504",
"ITEMUNIT": "EA",
"ORDERDETAILS": [
{
"SHIPDATEID": "69230",
"SHIPPERIODID": "2096",
"QUANTITY": "1"
},
{
"SHIPDATEID": "69231",
"SHIPPERIODID": "2096",
"QUANTITY": "2"
}
],
"SHIPPINGCOMMENTS": "sooner"
}
]
},
{
"compid": 920001,
"compname": null,
"products": [
{
"BCINUM": "539504",
"ITEMUNIT": "EA",
"ORDERDETAILS": [
{
"SHIPDATEID": "69230",
"SHIPPERIODID": "2096",
"QUANTITY": "1"
},
{
"SHIPDATEID": "69231",
"SHIPPERIODID": "2096",
"QUANTITY": "2"
}
],
"POTEXT": "",
"SHIPPINGCOMMENTS": "sooner"
}
]
}
]
}
Here is my code I am looping through it with:
function updateComments(compID,bcinum,comment) {
var accounts = runningOrders.accounts;
var n = accounts.length;
for (i = 0; i < n; i++) {
if (accounts[i].compid == compID) {
var p = accounts[i].products.length;
for (ii = 0; ii < p; ii++) {
if (accounts[i].products[ii].BCINUM == bcinum) {
accounts[i].products[ii].SHIPPINGCOMMENTS = comment;
}
}
}
}
}
The function call is:
updateComments(919759,539504,sooner);
Two potential issues:
When calculating n, you are actually not calculating the size of the acconts array? What is the name of your (JSON) object?
In your example function call, you are changing the name to the already defined name in both objects. Is this a mistake?
This code is working for me in node.js:
function updateComments(compID,bcinum,comment) {
var n = accounts.accounts.length;
console.log(n);
console.log(accounts['accounts'][0].products);
console.log(accounts['accounts'][1].products);
for (i = 0; i < n; i++) {
console.log('testing ', i, accounts.accounts[i].compid)
if (accounts.accounts[i].compid == compID) {
var p = accounts.accounts[i].products.length;
console.log('Found compid', i, compID);
for (ii = 0; ii < p; ii++) {
if (accounts.accounts[i].products[ii].BCINUM == bcinum) {
console.log('Found bcinum', ii, bcinum)
accounts.accounts[i].products[ii].SHIPPINGCOMMENTS = comment;
}
}
}
}
console.log(accounts['accounts'][0].products);
console.log(accounts['accounts'][1].products);
}
accounts = {
"id": 1402846607011,
"status": "unsaved",
"accounts":
[
{
"compid": 919759,
"compname": null,
"products": [
{
"BCINUM": "539504",
"ITEMUNIT": "EA",
"ORDERDETAILS": [
{
"SHIPDATEID": "69230",
"SHIPPERIODID": "2096",
"QUANTITY": "1"
},
{
"SHIPDATEID": "69231",
"SHIPPERIODID": "2096",
"QUANTITY": "2"
}
],
"SHIPPINGCOMMENTS": "sooner"
}
]
},
{
"compid": 920001,
"compname": null,
"products": [
{
"BCINUM": "539504",
"ITEMUNIT": "EA",
"ORDERDETAILS": [
{
"SHIPDATEID": "69230",
"SHIPPERIODID": "2096",
"QUANTITY": "1"
},
{
"SHIPDATEID": "69231",
"SHIPPERIODID": "2096",
"QUANTITY": "2"
}
],
"POTEXT": "",
"SHIPPINGCOMMENTS": "sooner"
}
]
}
]
}

data transformation from one form of array to another

I have doubt about data structure transformation from one form of array to another.
My input data is of the form,
var testVar=[
{
"count": 1,
"term": "Company",
"Company": [
{
"Tata": [
{
"count": 1,
"term": "Tatagroup"
}
],
"sector": "Automotive",
"type": "Car"
},
]
},
{
"count": 2,
"term": "Country",
"Country": [
{
"France": [
{
"count": 1,
"term": "France"
}
],
"region": "Europe",
"Player": "Zidane",
"term": "France",
"code": "FRA"
},
{
"region": "Europe",
"Player": "Federer",
"term": "Switzerland",
"Switzerland": [
{
"count": 1,
"term": "Switzerland"
}
],
"code": "SWI"
}
]
}];
and I am trying to transform it to the form,
[ "Tata" : [{"sector" : "automotive"}, "type" : "car"], "France": [{"region" : "Europe}, {"Player" : "Zidane"} , {"code" : "FRA"}], "switzerland" : [{"region" : "Europe}, {"Player" : "Federer"} , {"code" : "SWI"}]];
The code I came up with looks like http://jsfiddle.net/X2apw/2/, bt its nt accurate..
var testvar = [...];
var result = {};
for (var i=0; i<testvar.length; i++) {
var arr = testvar[i][testvar[i].term];
for (var j=0; j<arr.length; j++) {
var resarr = [];
for (var k in arr[j]) {
if (typeof arr[j][k] == "string") {
var obj = {};
obj[k] = arr[j][k];
resarr.push(obj);
} else {
result[k] = resarr;
}
}
}
}
(Demo at jsfiddle.net)
However, I strongly recommend to use just one object instead of an array of one-property-objects in your result format. Change the inner loop body to:
var resobj = {};
for (var k in arr[j]) {
if (typeof arr[j][k] == "string") {
resobj[k] = arr[j][k];
} else {
result[k] = resobj;
}
}
(Demo)

Categories