JSON object changes properties - javascript

I'm developing a chrome extension, I have to iterate through a dictionary and transfer data from the objects that are in there to another objects, I store the last ones in an array, this problem happened. Here is the output: json_object_err Here is the desired output:
Here is my code:
var active_observers = {};
var participants_data = [];
function save_partcipants_data() {
var participant_data = {
name: "",
words: 0,
id: "",
positive_marks: 0
}
for (let el in active_observers) {
var finded = false;
participant_data.name = active_observers[el].user_name;
participant_data.words = Math.round(active_observers[el].speak_counter / 2.15);
participant_data.id = active_observers[el].user_id;
participant_data.positive_marks = active_observers[el].positive_marks;
for (let i in participants_data) {
if (participants_data[i].name === participant_data.name) {
participants_data[i].words += participant_data.words;
participants_data[i].positive_marks += participant_data.positive_marks;
finded = true;
console.log("object:");
console.log(participant_data);
console.log("list:");
console.log(participants_data);
}
}
if (!finded) {
participants_data.push(participant_data);
console.log("object:");
console.log(participant_data);
console.log("list:");
console.log(participants_data);
}
}
}
active_observers[user_id] = {
"user_name": user_name,
"user_id": user_id,
"speak_counter": 0,
"user_observer": observer,
"positive_marks": 0
};
var active_observers = {};
var participants_data = [];
save_partcipants_data();

Related

How To Create Multiple Arrays From a Single Array?

I getting form data in my console like this:
{item[0][sku]: 'EC1000-WMK', item[0][qty]: '1', item[1][sku]: 'POP-11', item[1][qty]: '1', form_key: 'ZuQxqBMHmidjUxEt'}
form_key: "ZuQxqBMHmidjUxEt"
item[0][qty]: "1"
item[0][sku]: "EC1000-WMK"
item[1][qty]: "1"
item[1][sku]: "POP-11"
This is how the above data created:
$.fn.getFormData = function(){
var data = {};
var dataArray = $(this).serializeArray();
console.log(data);
console.log(dataArray);
for(var i=0;i<dataArray.length;i++){
console.log(dataArray);
data[dataArray[i].name] = dataArray[i].value;
}
return data;
}
but I want to make it like:
[
{ "sku": "EC1000-WMK", "qty": "1" }
{ "sku": "POP-11", "qty": "1" }
]
Use Input fields name be like
<input name="item.0.sku" />
<input name="item.0.qty" />
<input name="item.1.sku" />
<input name="item.2.qty" />
& then use this function
Here is the function which converts all form inputs to JSON format
const jsonSerialize = ($this) => {
$this = $this.find('input, select');
let data = {};
for (let i = 0; i < $this.length; i++) {
let el = $this[i];
let val = el.value;
if (!val) val = "";
let fullName = el.getAttribute("name");
if (!fullName) continue;
let fullNameParts = fullName.split('.');
let prefix = '';
let stack = data;
for (let k = 0; k < fullNameParts.length - 1; k++) {
prefix = fullNameParts[k];
if (!stack[prefix]) {
stack[prefix] = {};
}
stack = stack[prefix];
}
prefix = fullNameParts[fullNameParts.length - 1];
if (stack[prefix]) {
let newVal = stack[prefix] + ',' + val;
stack[prefix] += newVal;
} else {
stack[prefix] = val;
}
}
return data
}
let $form = $('form');
params = jsonSerialize($form)
Hope may this work for you

for loop in order to validate my values in reduxForm

I want to validate before submitting my values and in order not to write the same code for all the fields I want to create a for loop in order to validate all of them. More specifically:
const validate = values => {
const errors = {};
if (!values.measuring_point) {
errors.measuring_point = i18n.t("Required");
}
if (values.image) {
if (!/^image.*$/.test(values.image.type)) {
errors.image = i18n.t("Only image files are allowed");
}
}
let i = null;
let measurements = [values.measurement_1, values.measurement_2, values.measurement_3, values.measurement_4, values.measurement_5, values.measurement_6];
let errors_measurements = [errors.measurement_1, errors.measurement_2, errors.measurement_3, errors.measurement_4, errors.measurement_5, errors.measurement_6];
let types = [values.measurement_type_1, values.measurement_type_2, values.measurement_type_3, values.measurement_type_4, values.measurement_type_5, values.measurement_type_6];
let errors_types = [errors.measurement_type_1, errors.measurement_type_2, errors.measurement_type_3, errors.measurement_type_4, errors.measurement_type_5, errors.measurement_type_6];
let unit = [values.measurement_unit_1, values.measurement_unit_2, values.measurement_unit_3, values.measurement_unit_4, values.measurement_unit_5, values.measurement_unit_6];
let errors_unit = [errors.measurement_unit_1, errors.measurement_unit_2, errors.measurement_unit_3, errors.measurement_unit_4, errors.measurement_unit_5, errors.measurement_unit_6];
for (i = 1; i < 7; i++) {
if (types[i] && measurements[i] && !unit[i]) {
errors_unit[i] = i18n.t("Required");
}
}
return errors;};
But it does not work and it does not give any error
I fixed it Tho Vu you were right:
const validate = values => {
const errors = {};
if (!values.measuring_point) {
errors.measuring_point = i18n.t("Required");
}
if (values.image) {
if (!/^image.*$/.test(values.image.type)) {
errors.image = i18n.t("Only image files are allowed");
}
}
let measurements = [
values.measurement_1,
values.measurement_2,
values.measurement_3,
values.measurement_4,
values.measurement_5,
values.measurement_6
];
let errors_measurements = [
errors.measurement_1,
errors.measurement_2,
errors.measurement_3,
errors.measurement_4,
errors.measurement_5,
errors.measurement_6
];
let types = [
values.measurement_type_1,
values.measurement_type_2,
values.measurement_type_3,
values.measurement_type_4,
values.measurement_type_5,
values.measurement_type_6
];
let errors_types = [
errors.measurement_type_1,
errors.measurement_type_2,
errors.measurement_type_3,
errors.measurement_type_4,
errors.measurement_type_5,
errors.measurement_type_6
];
let unit = [
values.measurement_unit_1,
values.measurement_unit_2,
values.measurement_unit_3,
values.measurement_unit_4,
values.measurement_unit_5,
values.measurement_unit_6
];
let errors_unit = [
"measurement_unit_1",
"measurement_unit_2",
"measurement_unit_3",
"measurement_unit_4",
"measurement_unit_5",
"measurement_unit_6"
];
for (let i = 0; i < 6; i++) {
if (types[i] && measurements[i] && !unit[i]) {
errors[errors_unit[i]] = i18n.t("Required");
}
}
return errors;};

I don't understand why this is not working (javascript object for roof)

I wnat to make JSON string with object.
but i got some weird problem.
The object changes the previous value.
I do not know the reason..
my code is..
var sStr = "L1^P1^Viscosity:vp1,L1^P2^Viscosity:vp2,L1^P3^Viscosity:vp3,L1^P4^Viscosity:vp4,L1^P5^Viscosity:vp5"
var objChild1 = {};
var objChild2 = {};
var objRtn = {};
var arrStr = sStr.split(',');
for (var i = 0; i < arrStr.length; i++) {
var arrSpe = arrStr[i].split('^');
objChild2["" + arrSpe[2].split(':')[0] + ""] = arrSpe[2].split(':')[1];
objChild1["" + arrSpe[1] + ""] = objChild2;
objRtn["" + arrSpe[0] + ""] = objChild1;
}
var sOp = JSON.stringify(objRtn, null, 2);
I think the result of this logic is
{
"L1": {
"P1": {
"Viscosity": "vp1"
},
"P2": {
"Viscosity": "vp2"
},
"P3": {
"Viscosity": "vp3"
}
...
}
}
this.. but The result is
{
"L1": {
"P1": {
"Viscosity": "vp5"
},
"P2": {
"Viscosity": "vp5"
},
"P3": {
"Viscosity": "vp5"
}
...
}
}
I always seem to be asking foolish questions.
But I have no one to ask.
Why is this happening?
And let me know what the key to this problem is.
You're using the same objChild1 and objChild2 objects each time through the loop. You need to create new objects each time, but only when the property name is one that hasn't been created already.
var sStr = "L1^P1^Viscosity:vp1,L1^P2^Viscosity:vp2,L1^P3^Viscosity:vp3,L1^P4^Viscosity:vp4,L1^P5^Viscosity:vp5";
var arrStr = sStr.split(',');
var objRtn = {};
for (var i = 0; i < arrStr.length; i++) {
var arrSpe = arrStr[i].split('^');
var lnum = arrSpe[0];
var pnum = arrSpe[1];
var prop = arrSpe[2].split(':');
var propname = prop[0];
var propval = prop[1];
if (!objRtn[lnum]) {
objRtn[lnum] = {};
}
if (!objRtn[lnum][pnum]) {
objRtn[lnum][pnum] = {};
}
objRtn[lnum][pnum][propname] = propval;
}
console.log(JSON.stringify(objRtn, null, 2));

Javascript closure not displaying content

I am trying to do this function closure but its displaying in the console as:
function NewsAPI() {
var authorOfArticle = [], descriptionOfArticle = [], publishedAtDate = [], titleOfArticle = [], urlOfArticle = [], urlToImageOfArticle = [];
var newsConstructor = new XMLH…
I looked at my code and switched things around but all of my attempts failed. Now i need some outside help. Here is my code:
function NewsAPI() {
var authorOfArticle = [],
descriptionOfArticle = [],
publishedAtDate = [],
titleOfArticle = [],
urlOfArticle = [],
urlToImageOfArticle = [];
var newsConstructor = new XMLHttpRequest(),
url = 'https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=c99bdac4799a421cbe9fd3589b60397d',
InnerNewsAPI;
newsConstructor.onreadystatechange = function() {
if (newsConstructor.readyState === 4 && newsConstructor.status === 200) {
var response = newsConstructor.responseText,
parsedNews = JSON.parse(response);
for (var i = 0; i < parsedNews["articles"].length; i++) {
authorOfArticle.push(parsedNews["articles"][i].author); // [0] = author
descriptionOfArticle.push(parsedNews["articles"][i].description); // [1] = description of article
publishedAtDate.push(parsedNews["articles"][i].publishedAt); // [2] = date published
titleOfArticle.push(parsedNews["articles"][i].title); // [3] = title
urlOfArticle.push(parsedNews["articles"][i].url); // [4] link to source
urlToImageOfArticle.push(parsedNews["articles"][i].urlToImage); // [5] = image url
}
console.log(titleOfArticle);
InnerNewsAPI = function() {
$("document").ready(function() {
$("#a1title").text(titleOfArticle[0]).addClass("article articletitles");
$("#a1author").text("Author: " + authorOfArticle[0]).addClass("articleauthors");
$("#a1source").attr("href", urlOfArticle[0]).text(urlOfArticle[0]).addClass("articles articlesources");
$("#a1image").attr("src", urlToImageOfArticle[0]).addClass("article articleimages");
$("#a1description").text(descriptionOfArticle[0]).addClass("articledescriptions");
$("#a2title").text(titleOfArticle[1]).addClass("article articletitles");
$("#a2author").text("Author: " + authorOfArticle[1]).addClass("articleauthors");
$("#a2source").attr("href", urlOfArticle[1]).text(urlOfArticle[1]).addClass("articles articlesources");
$("#a2image").attr("src", urlToImageOfArticle[1]).addClass("article articleimages");
$("#a2description").text(descriptionOfArticle[1]).addClass("articledescriptions");
return urlOfArticle;
}); // put code above this line
}
};
return InnerNewsAPI;
}
newsConstructor.open("GET", url, true);
newsConstructor.send(null);
//return InnerNewsAPI;
//return innerNewsAPI();
}
console.log(NewsAPI);

Javascript: group JSON objects using specific key

I have the following JSON object and wanted to merge them by OrderID, making the items into array of objects:
[
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
]
and I'm wondering how in Javascript to merge the items on the same order...like this:
[{
"OrderID": "999123",
"Items": [{
"ItemCode": "DY-FBBO",
"ItemQuantity": "2",
"ItemName": "DOIY Foosball Bottle Opener > Red",
"ItemPrice": "34.95"
}, {
"ItemCode": "TED-072",
"ItemQuantity": "1",
"ItemName": "Ted Baker Womens Manicure Set",
"ItemPrice": "74.95"
}]
}]
I suggest you use javascript library like underscorejs/lazyjs/lodash to solve this kind of thing.
Here is the example on using underscorejs:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}]
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
Working example:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}];
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
This should do what you want it to do, but it's rather a group function than a merge function :)
You can see the result in the browser console.
var items = [
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
];
function groupBy(ungrouped, groupByProperty) {
var result = [],
getGroup = function (arr, val, groupByProperty) {
var result, j, jlen;
for (j = 0, jlen = arr.length; j < jlen; j++) {
if (arr[j][groupByProperty] === val) {
result = arr[j];
break;
}
}
if (!result) {
result = {};
result.items = [];
result[groupByProperty] = val;
arr.push(result);
}
return result;
}, i, len, item;
for (i = 0, len = ungrouped.length; i < len; i++) {
item = getGroup(result, ungrouped[i][groupByProperty], groupByProperty);
delete ungrouped[i][groupByProperty];
item.items.push(ungrouped[i]);
}
return result;
}
var grouped = groupBy(items, 'OrderID');
document.getElementById('result').innerHTML = JSON.stringify(grouped);
console.log(grouped);
<div id="result"></div>
Lodash is a great Javascript Utility library that can help you in this case. Include the latest version of lodash in your code and group the objects like this:
var mergedOrders = _.groupBy(OriginalOrders, 'OrderID');
It seems you'll have to do a function that, for each entry, will check if it match
try this :
// your array is oldArr
var newArr = []
for (var i=0;i<oldArr.length;i++){
var found = false;
for(var j=0;j<newArr.length;j++){
if(oldArr[i]["OrderID"]==newArr[j]["OrderID"]){
newArr[j]["Items"].push(oldArr[i]);
found=true;
break;
}
if(!found){
newArr.push({"OrderID" : oldArr[i]["OrderID"], "Items" : oldArr[i]});
}
}
You need to loop and create new grouped objects according to your requirement.
For an easier approach I would suggest using jquery-linq
var qOrderIds = $.Enumerable.From(myArray).Select(function(item) { return item.OrderID; }).Distinct();
var groupedList = qOrderIds.Select(function(orderId) {
return {
OrderID: orderId,
Items : $.Enumerable.From(myArray).Where(function(item) { item.OrderID === orderId}).ToArray()
};
}).ToArray();
Thank you for all your answers.
I was able to attain my goal (maybe a bit dirty and not as beautiful as yours but it worked on my end). Hoping this might help others in the future:
function processJsonObj2(dataObj, cfg) {
var retVal = dataObj.reduce(function(x, y, i, array) {
if (x[cfg.colOrderId] === y[cfg.colOrderId]) {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
delete x[cfg.colOrderId];
delete y[cfg.colOrderId];
delete x[cfg.colAddressee];
delete y[cfg.colAddressee];
delete x[cfg.colCompany];
delete y[cfg.colCompany];
delete x[cfg.colAddress1];
delete y[cfg.colAddress1];
delete x[cfg.colAddress2];
delete y[cfg.colAddress2];
delete x[cfg.colSuburb];
delete y[cfg.colSuburb];
delete x[cfg.colState];
delete y[cfg.colState];
delete x[cfg.colPostcode];
delete y[cfg.colPostcode];
delete x[cfg.colCountry];
delete y[cfg.colCountry];
delete x[cfg.colOrderMessage];
delete y[cfg.colOrderMessage];
delete x[cfg.colCarrier];
delete y[cfg.colCarrier];
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ x, y ];
return orderObj;
} else {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
var itemCode = x[cfg.colItemCode];
var itemQuantity = x[cfg.colItemQuantity];
var itemName = x[cfg.colItemName];
var itemPrice = x[cfg.colitemPrice];
var item = {};
item[cfg.colItemCode] = itemCode;
item[cfg.colItemQuantity] = itemQuantity;
item[cfg.colItemName] = itemName;
item[cfg.colItemPrice] = itemPrice;
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ item ];
return orderObj;
}
});
return retVal;
}

Categories