Append text to a value in a json arrray - javascript

How can I append a text to only the first value of an array and send the array back to the server. This is the response i am getting from the server
[{
"12": [ "12", "1", "2", "3" ]
}, {
"13": [ "13", "1", "2", "3" ]
}, {
"14": [ "14", "1", "2", "3" ]
}, {
"15": [ "15", "1", "2", "3" ]
}]
I want my array to now be like this so that i can pass this array to my data table.
var object = [{
12: ["12 hrs", "1", "2", "3"]
}, {
13: ["13 hrs", "1", "2", "3"]
}, {
14: ["14 hrs", "1", "2", "3"]
}, {
15: ["15 hrs", "1", "2", "3"]
}]
How can I append hrs to the first value?

Here's one easy method...
// Parse the string response from the server into an object
var obj = JSON.parse(serverResponse);
// loop through the object, knowing that it's nested in the first index of an array "obj[0]"
for(id in obj[0]){
// obj->arrayIndex->objectProperty->arrayIndex append " hrs"
obj[0][id][0] += " hrs";
}
// to return this to the server, apply JSON.stringify(obj)

I fixed object in your question to -
var objectArray = [{"12" : ["12", "1", "2", "3"]}, {"13" : ["13", "1", "2", "3"]},{"14" : ["14", "1", "2", "3"]},{"15" : ["15", "1", "2", "3"]}]
This is how you can loop through the objectArray and change in the way you wanted -
for(var i=0;i<objectArray.length;i++)
{
for(var key in objectArray[i])
{
objectArray[i][key][0]+=" hrs";
break;
}
}
console.log(objectArray)

Related

Get array of same object from two arrays

the first one is a global list of products (say 10 products) that each product contains a code and a quantity greater than or equal to 0. (this is important)
the second is a list of products (say 3) that each product contains a code (the same as in the first table) and a quantity equal to 0.
I want to filter the first array and have an array with 3 product but keep the quantities of the first one
for example:
state.Data = [
{
"code": "0",
"qte": "0"
},
{
"code": "1",
"qte": "0"
},
{
"code": "2",
"qte": "14"
},
{
"code": "3",
"qte": "14"
},
{
"code": "4",
"qte": "0"
},
{
"code": "5",
"qte": "0"
},
{
"code": "6",
"qte": "0"
},
{
"code": "7",
"qte": "0"
},
{
"code": "8",
"qte": "0"
},
{
"code": "9",
"qte": "0"
}
];
action.value.Data = [
{
"code": "0",
"qte": "0"
},
{
"code": "2",
"qte": "0"
},
{
"code": "3",
"qte": "0"
}
];
// what I want:
result = [
{
"code": "0",
"qte": "0"
},
{
"code": "2",
"qte": "14"
},
{
"code": "3",
"qte": "14"
}
];
the difference between action.value.Data and result is qte of each product.
I had tried:
const mainData = [...action.value.Data,...state.Data];
var catData = mainData.reduce((p, c) => {
p[c.code] = (p[c.code] || 0) ;
return p;
}, {});
var result = mainData.filter((obj) => {
return catData[obj.code] >= 0;
});
nextState = {
...state,
Data: result,
}
but the result table gives me 6 products instead of 3 (always double) and the qte is always 0, so how to filter the state.Data array and keep only the products which have the same code as in the action.value.Data array
I can not understand the logic of your code actually. Solution is extremely simple
// step 1: getting keys
const keys = action.value.Data.map(v => v.code)
// step 2: filter values with these keys
const values = state.Data.filter(v => keys.includes(v.code))
That's it
This can be easily done with one liner. All you want to do is filter the first array checking which items are on the second array:
const result = state.Data.filter(({code}) =>
action.value.Data.some(x => x.code === code))
console.log(result)
You get exactly the value you want.
const state = {Data:[
{"code": "0","qte": "0"},{"code": "1","qte": "0"},{"code": "2","qte": "14"},{"code": "3","qte": "14"},
{"code": "4","qte": "0"},{"code": "5","qte": "0"},{"code": "6","qte": "0"},{"code": "7","qte": "0"},
{"code": "8","qte": "0"},{"code": "9","qte": "0"}
]},
action = {value:{Data:[
{"code": "0","qte": "0"},{"code": "2","qte": "0"},{"code": "3","qte": "0"}
]}};
const res = state.Data.filter(o=>action.value.Data.some(a=>a.code==o.code));
console.log(res)
You can just filter the global products based on the codes in action.value.Data but you can also try the below solution to avoid nested loops.
Create a map with code as keys, qte as values and use it while mapping the action.value.Data.
const global = [{
"code": "0",
"qte": "0"
},
{
"code": "1",
"qte": "0"
},
{
"code": "2",
"qte": "14"
},
{
"code": "3",
"qte": "14"
},
{
"code": "4",
"qte": "0"
},
{
"code": "5",
"qte": "0"
},
{
"code": "6",
"qte": "0"
},
{
"code": "7",
"qte": "0"
},
{
"code": "8",
"qte": "0"
},
{
"code": "9",
"qte": "0"
}
];
const bla = [{
"code": "0",
"qte": "0"
},
{
"code": "2",
"qte": "0"
},
{
"code": "3",
"qte": "0"
}
];
const codeVsQty = new Map(global.map(({code, qte}) => [code, qte]));
const result = bla.map(({code}) => ({code, qte: codeVsQty.get(code)}));
console.log(result)

Compare Object properties that contain array with each other to find difference

Problem:
I am working on a mini project involving a JSON file and express/nodejs and I am stuck on a portion that contains the following instructions:
Using a post route, determine the user's most compatible friend using
the following rules: Convert each user's results into a simple array
of numbers.
Compare the difference between current user's scores against those
from potential matches, question by question. Add up the differences
to calculate the totalDifference.
Example: User 1: [5, 1, 4, 4, 5, 1, 2, 5, 4, 1] User 2: [3, 2, 6, 4,
5, 1, 2, 2, 4, 1]
Total Difference: 2 + 1 + 2 + 3 = 8
Remember to use the absolute value of the differences; no negative
results! Your app should calculate both 5-3 and 3-5 as 2, etc.
I am able to get the results that look like this (the submitted array is the last array all 5's):
Here is the portion of code I am using for that:
app.post('/surveyResponse', function(req,res){
let photo = req.body.url;
let name = req.body.name;
let travel = req.body.travel;
let affection = req.body.affection;
let family = req.body.family;
let fitness = req.body.fitness;
let movie = req.body.movie;
let education = req.body.education;
let career = req.body.career;
let marriage = req.body.marriage;
let children = req.body.children;
let pets = req.body.pets;
let sum = 0;
let obj = {};
let person = {
name: name,
photo: photo,
scores: [
travel,
affection,
family,
fitness,
movie,
education,
career,
marriage,
children,
pets
]
}
//finding the sum of all the numbers
for(i in person.scores){
sum+=Number(person.scores[i]);
}
//form submission results
let score = person.scores;
// Read the file and send to the callback
fs.readFile('./app/data/friends.json', handleFile)
// Write the callback function
function handleFile(err, data) {
if (err) throw err
obj = JSON.parse(data)
for(var key in obj){
var obj2 = obj[key];
console.log(obj2.scores);
}
//this is the console.log for my form submission array
console.log(score);
}
//------------------------------------
// result that prints out on the HTML
res.send('Your name is ' + name + ' You Score is ' + sum );
});
GOAL
The goal is the find the user with the least difference between their results and what the user submitted.
RESEARCH
I have done research How to compare each object in an array with each other. When found update the object with a new property How to Subtract Multiple Objects from an Array with Another array
and most of the examples deal with having separate JSON objects and comparing them to each other and the one I found that compared an array of JSON objects was just comparing phone numbers. I am stuck on my next steps. I just need a jump start/guidance please.
Here is the JSON file I am working with:
[
{
"name": "Mike Jackson",
"photo": "./app/public/matchPhotos/photo0.jpg",
"scores": [
"3",
"2",
"4",
"3",
"3",
"4",
"4",
"4",
"3",
"4"
]
},
{
"name": "Jermaine Subia",
"photo": "./app/public/matchPhotos/photo1.jpg",
"scores": [
"4",
"4",
"2",
"2",
"4",
"5",
"3",
"4",
"5",
"2"
]
},
{
"name": "Taji Gibson",
"photo": "./app/public/matchPhotos/photo2.jpg",
"scores": [
"1",
"5",
"3",
"2",
"3",
"1",
"3",
"4",
"3",
"3"
]
},
{
"name": "Jamie Schully",
"photo": "./app/public/matchPhotos/photo3.jpg",
"scores": [
"5",
"3",
"3",
"4",
"2",
"4",
"4",
"5",
"5",
"5"
]
},
{
"name": "Justin Andres",
"photo": "./app/public/matchPhotos/photo4.jpg",
"scores": [
"2",
"1",
"1",
"1",
"2",
"3",
"2",
"2",
"2",
"4"
]
},
{
"name": "Austin Brooks",
"photo": "./app/public/matchPhotos/photo5.jpg",
"scores": [
"2",
"3",
"4",
"2",
"4",
"4",
"4",
"4",
"5",
"4"
]
},
{
"name": "Jessica Jones",
"photo": "./app/public/matchPhotos/photo6.jpg",
"scores": [
"4",
"4",
"4",
"4",
"4",
"4",
"4",
"4",
"5",
"4"
]
},
{
"name": "Jasmine Love",
"photo": "./app/public/matchPhotos/photo7.jpg",
"scores": [
"4",
"3",
"3",
"2",
"2",
"2",
"2",
"1",
"2",
"1"
]
},
{
"name": "Sandra Smith",
"photo": "./app/public/matchPhotos/photo8.jpg",
"scores": [
"1",
"2",
"2",
"2",
"4",
"3",
"4",
"3",
"3",
"1"
]
},
{
"name": "Kevin Hart",
"photo": "./app/public/matchPhotos/photo9.jpg",
"scores": [
"5",
"5",
"3",
"3",
"2",
"2",
"5",
"5",
"4",
"3"
]
}
]
UPDATE 1
I am trying to incorporate the following code but am not understanding as to why I keep getting the following error:
ReferenceError: data is not defined
I believe it has to do with how I am trying to incorporate the incoming data. I took the code and tried to translate it to fit my code.
// Read the file and send to the callback
fs.readFileSync('./app/data/friends.json', findCompatibility); <---- This is the line I think is causing issues
// Write the callback function
function findCompatibility(data) {
var results = [];
for (let i = 0; i < data.length; i++) {
for (let j = 1; j < data.length - 1; j++) {
const user1 = data[i];
const user2 = data[j];
var difference = 0;
for (let k = 0; k < user1.scores.length; k++) {
difference += Math.abs(Number(user1.scores[k]) - Number(user2.scores[k]));
}
results.push({"name": user1.name, "friend": user2.name, "difference": difference});
}
}
return results;
}
console.log(findCompatibility(data));
Some pointers to point you in right direction:
To ensure that differences aren't negative use Math.abs() to get the absolute value of the difference.
Right now all the scores are strings, convert them to number using Number() or parseInt().
var data = [ { "name": "Mike Jackson", "photo": "./app/public/matchPhotos/photo0.jpg", "scores": [ "3", "2", "4", "3", "3", "4", "4", "4", "3", "4" ] }, { "name": "Jermaine Subia", "photo": "./app/public/matchPhotos/photo1.jpg", "scores": [ "4", "4", "2", "2", "4", "5", "3", "4", "5", "2" ] }, { "name": "Taji Gibson", "photo": "./app/public/matchPhotos/photo2.jpg", "scores": [ "1", "5", "3", "2", "3", "1", "3", "4", "3", "3" ] }, { "name": "Jamie Schully", "photo": "./app/public/matchPhotos/photo3.jpg", "scores": [ "5", "3", "3", "4", "2", "4", "4", "5", "5", "5" ] }, { "name": "Justin Andres", "photo": "./app/public/matchPhotos/photo4.jpg", "scores": [ "2", "1", "1", "1", "2", "3", "2", "2", "2", "4" ] }, { "name": "Austin Brooks", "photo": "./app/public/matchPhotos/photo5.jpg", "scores": [ "2", "3", "4", "2", "4", "4", "4", "4", "5", "4" ] }, { "name": "Jessica Jones", "photo": "./app/public/matchPhotos/photo6.jpg", "scores": [ "4", "4", "4", "4", "4", "4", "4", "4", "5", "4" ] }, { "name": "Jasmine Love", "photo": "./app/public/matchPhotos/photo7.jpg", "scores": [ "4", "3", "3", "2", "2", "2", "2", "1", "2", "1" ] }, { "name": "Sandra Smith", "photo": "./app/public/matchPhotos/photo8.jpg", "scores": [ "1", "2", "2", "2", "4", "3", "4", "3", "3", "1" ] }, { "name": "Kevin Hart", "photo": "./app/public/matchPhotos/photo9.jpg", "scores": [ "5", "5", "3", "3", "2", "2", "5", "5", "4", "3" ] } ];
function findCompatibility(data) {
var results = [];
for (let i = 0; i < data.length; i++) {
for (let j = 1; j < data.length - 1; j++) {
const user1 = data[i];
const user2 = data[j];
var difference = 0;
for (let k = 0; k < user1.scores.length; k++) {
difference += Math.abs(Number(user1.scores[k]) - Number(user2.scores[k]));
}
results.push({"name": user1.name, "friend": user2.name, "difference": difference});
}
}
return results;
}
console.log(findCompatibility(data));
var arr1 = [1,4,7,88,40];
var arr2 = [1,77,3,45];
function diff(a1, a2){
var s1 = a1.reduce((red,n) => red+n);
var s2 = a2.reduce((red,n) => red+n);
var total = s1 - s2;
return total >= 0 ? total : -1*total;
}
console.log(diff(arr2, arr1));

How to make a new array of strings derived from an old array, using a delimeter

I have an array of strings and I want to make a new one joining the strings of the arrays until the delimeter character is shown.For example I have this array of strings:
["5", "2", "0", "1", "6", "2", "7", "0", "1", "9", "9", "0", "0", "", "5", "2", "0", "3", "4", "1", "1", "0", "2", "1", "9", "8", "4", ""]
and I want to make a new one like this:
["5201627019900","5203411021984"]
The delimeter of those items in the array is the "" between them.Any help?
var result = array.join("").trim().split(/\s/ /*or " " */);
var result = array.reduce((a,b) => { return a+b; }).trim().split(" ");

Get KEY from JSON

Following JSON : https://api.myjson.com/bins/3yz34
I was thinking I might use an internal ID for a key (which simplifies looping through several entities and setting up data gathering) and use a value for display. However, I cannot get the value of the key.
$.each(tabledata.Companies, function (){
company = this;
alert(company);
var test = Object.keys( company );
console.log(test);
});
Object.keys() just gives me the number of characters in the value.
var test = Object.keys( company );
Returns:
["0", "1", "2", "3", "4", "5", "6", "7"]
["0", "1", "2", "3", "4", "5", "6", "7", "8"]
["0", "1", "2", "3", "4", "5", "6"]
["0", "1", "2", "3", "4"]
["0", "1", "2", "3", "4", "5", "6"]
Which seems to be the number of characters from the value in the key-value pair? Pretty stuck on this one, any ideas? Or maybe setup the JSON differently?
Thanks in advance!
Change the signature of your loop function to pass in the parameters
$.each(tabledata.Companies, function(key, value) {...}
See demo below
DEMO UPDATED based on comments
var tabledata = {
"Companies": {
"8df135f4-db42-486c-8d8c-fbbdd561c25e": "Phillips",
"47d946e3-56db-4bc7-8472-3809eb48506d": "Bauknecht",
"3ae13b97-7a09-4342-8953-c1d5a55687db": "Capitol",
"fb017214-dbc1-4b71-8080-4f9b530f4b49": "Bosch",
"50ede412-4eb0-429b-8d73-a1bfef41ebbc": "LG Corp"
},
"Pets": {
"dog": "Snoopy",
"cat": "Silvester",
"bird": "Sweetie",
"snake": "Snaker",
"fish": "Goldie Locks"
}
}
var attributeName="Companies";
$(function() {
$.each(tabledata[attributeName], function(key, value) {
console.log("KEY:" + key + " -> Value:" + value);
});
attributeName="Pets";
$.each(tabledata[attributeName], function(key, value) {
console.log("KEY:" + key + " -> Value:" + value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Access JSON data returned from CMS

The CMS I am using will give me JSON data of each item within a database. I use the following code to access this data:
var items = new BCAPI.Models.WebApp.ItemCollection("Strain Bank");
items.fetch({
success: function (items) {
items.each(function (item) {
item.fetch({
success: function (itemDetails) {
console.log(JSON.stringify(itemDetails.attributes))
}
});
});
}
});
This console.log(JSON.stringify(itemDetails.attributes)) outputs the following code for each item. An example of an items code is below:
{
"id": 4441485,
"name": "Alien OG",
"fields": {
"Buzz Length": "580",
"Strength": "37",
"Sativa Percentage": "231",
"Overall Rating": "40",
"Flower Time": "61",
"Potency": "10",
"Yield": "10",
"Height": "20",
"Reviews": "4",
"Grow Reviews": "1",
"Creative": "2",
"Euphoric": "0",
"Uplifted": "0",
"Energetic": "2",
"Lazy": "0",
"Focused": "2",
"Happy": "1",
"Talkative": "0",
"Giggly": "0",
"Tingly": "0",
"Hungry": "0",
"Sleepy": "0",
"Aroused": "0",
"Migraines": "1",
"Nausea": "0",
"Insomnia": "0",
"Pain": "2",
"Anxiety": "0",
"Stress": "2",
"PMS": "0",
"Lack of Appetite": "0",
"Muscle Spasms": "0",
"Depression": "2",
"Seizures": "0",
"Fatigue": "1",
"Fruity": "0",
"Citrus": "0",
"Seasonings-Spicy": "1",
"Floral": "2",
"Pungent": "2",
"Chemical": "1",
"Earthy": "2",
"Sweet": "0",
"Grass": "1",
"Skunky": "0"
}
}
What I need to do is access the data within each item. I am unsure how to do this. I tried:
//Thecode below replaces console.log(JSON.stringify(itemDetails.attributes)) in the above example.
var json = JSON.stringify(itemDetails.attributes)
$.each($.parseJSON(json), function(idx, obj) {
console.log(obj.name);
});
When I try the above code I see two things in the console.log:
TypeError: obj is null
and
undefined
How do I properly access the JSON data?
You should be able to access data in each item by . notation, like itemDetails.attributes.id, itemDetails.attributes.name and itemDetails.attributes.fields
Replace below:
console.log(JSON.stringify(itemDetails.attributes))
With below and try
console.log(itemDetails.attributes.name);
You are accessing the desired object wrongly. Try,
$.each(xObj.fields, function (key, val) {
console.log(key + " : " + val);
});
DEMO

Categories

Resources