I have having trouble figuring out how I can limit my output. I have to compare values of each attribute within an object, however I only want 1 output per ID.
Any thoughts?
//example JSON
var obj1 = {
"Summary" :
[
{
"ID" : "1234",
"Name" : "John",
"Status" : "Green",
},
{
"ID" : "5678",
"Name" : "Mike",
"Status" : "Green",
},
{
"ID" : "9012",
"Name" : "Tom",
"Status" : "Red",
}
]
};
//my code
var attributesvalues = ["Mike", "Green", "Red"];
var sg1 = [];
var k;
var l;
//push name of each attribute value to a new array
//one example
sg1.push(attributesvalues[0]);
//go through each ID, if name value exist, push the #1, if not, push nothing
for (k = 0; k < obj1.Summary.length; k++) {
for (l in obj1.Summary[k]) {
if (sg1[0] == obj1.Summary[k][l]){
sg1.push("1");
}
else{
sg1.push("");
}
}
}
output should look like this - I only want 4 values, name + a 1 or "" for each ID(3)
sg1 = ["Mike", "", "1", ""]
sg2 = ["Green", "1", "1", ""]
instead I am getting this - the name + a 1 or "" for each attribute.
sg1 = ["Mike", "", "", "", "", "1", "", "", "", ""]
sg2 = ["Green", "", "", "1", "", "", "1", "", "", ""]
Any additional pointers or tips you could provide would be much appreciated. I am still trying to get the hang of JS.
You don't know if you have a match or not until you finish the entire for-in loop.
var found;
for (k = 0; k < obj1.Summary.length; k++) {
found = "";
for (l in obj1.Summary) {
if (obj1.Summary[i][l] == sg1[0]) {
found = "1";
break;
}
}
sg1.push(found);
}
Related
Am having the arrays,
Now i need to get all tab names looping through and exclude the values present in exclude.
json1 ={
"sku Brand": "abc",
"strngth": "ALL",
"area": "",
"Country": "",
"local Brand": "",
"theme": "HideDisNameFilters"
}
json2 = {
"nav": [{
"tabname": "tab1",
"exclude':["area',"xyz"]
},
{
"tabname": "tab2",
"exclude":["Country"]
}
]}
var obj1 = json2.nav;
console.log(obj1)
Object.keys(obj1).forEach(function(prop) {
var str1 = "";
var maxLength = Object.keys(json1).length-2
Object.keys(json1).forEach(key => {
var str = "";
var t1 = "";
var index = Object.keys(json1).indexOf(key);
if(key != "theme"){
if(!obj1[prop]['exclude'].includes(key)){
str = key + "="+ json1[key];
str1 +=str&
console.log("str",str, " = ",str1 )
if(maxLength == index){
var t1 = "<a href="+str1 + "target='_blank'>"+ obj1[prop]['tabname'] +"</a>"
final_array.push(t1)
}
}
}
});
});
o/p should be: (it will exclude and form the url by checking from exclude array as below)
["<a href='sku+Brand=abc&Strngth=ALL&Country=&local+Brand=&' "target='_blank'>tab1<a>,"<a href='sku+Brand=abc&Strngth=ALL&area=&local+Brand=&' "target='_blank'>tab2<a>"]
AM not getting the correct output as expected...
Your code has several syntax errors (unbalanced quotes, mismatching quotes, trailing & without quotes, ...), and variables that have not been defined with var, let or const. It assigns to key_for_url, but never uses that value. It references a "slug" property, but that doesn't exist in your input data. It assumes a certain key order in plain objects, as it uses indexOf on Object.keys. This is a code smell. Variable names json1 and json2 are not very descriptive.
Here is code you could use:
let filter = {
"sku Brand": "abc",
"strngth": "ALL",
"area": "",
"Country": "",
"local Brand": "",
"theme": "HideDisNameFilters"
}
let tabs = {
"nav": [{
"tabname": "tab1",
"exclude": ["area", "xyz"]
},
{
"tabname": "tab2",
"exclude": ["Country"]
}
]
}
let result = tabs.nav.map(({tabname, exclude}) =>
`<a href='${
Object.entries(filter)
.filter(([key]) => !exclude.includes(key) && key != "theme")
.map(([key, value]) => `${key}=${value}`)
.join("&")
}' target='_blank'>${tabname}</a>`
);
console.log(result);
Solution:
obj1 is an array, so the loop will be obj1.forEach and accessing the value will be prop['exclude'].
I have made the code a bit more short.
json1 = {
"sku Brand": "abc",
"strngth": "ALL",
"area": "",
"Country": "",
"local Brand": "",
"theme": "HideDisNameFilters"
}
json2 = {
"nav": [{
"tabname": "tab1",
"exclude": ["area", "xyz"]
},
{
"tabname": "tab2",
"exclude": ["Country"]
}
]
}
final_array = []
var obj1 = json2.nav;
obj1.forEach(function (prop) {
let str = "";
Object.keys(json1).forEach((key) => {
if (!prop['exclude'].includes(key) && key !== 'theme') {
newKey = key.split(' ').join('+');
str = str + newKey + '=' + json1[key] + "&";
}
})
var t1 = "<a href=" + "'" + str + "'" + " target = '_blank' > "+ prop['tabname'] +" < /a>"
final_array.push(t1)
});
console.log(final_array)
I have an array of objects with some properties as string values, can someone help me to get array of numbers out it. Here is the array looks like.
scores = [
{
maxScore:"100"
obtainedScore:"79"
passed:"pass"
subject:"Maths"
},
{
maxScore:"100"
obtainedScore:"73"
passed:"pass"
subject:"Science"
},
{
maxScore:"100"
obtainedScore:"82"
passed:"pass"
subject:"English"
}
]
i want obtainedScore and maxScore should be taken out from these objects and place them in two different arrays
i tried this
for (var i =0 ; i < score.length; i++)
{
var marks[i] = parseInt(score[i].obtainedScore) ;
}
and i found NaN.
CORRECT ANSWER BASED ON YOUR ATTEMPT:
var scores = [{
maxScore: "100",
obtainedScore: "79",
passed: "pass",
subject: "Maths"
}, {
maxScore: "100",
obtainedScore: "73",
passed: "pass",
subject: "Science"
}, {
maxScore: "100",
obtainedScore: "82",
passed: "pass",
subject: "English"
}]
var marks = [];
for (var i = 0; i < scores.length; i++) {
marks[i] = parseInt(scores[i].obtainedScore, 10);
}
console.log(marks)
MY SOLN (from before you editted in your attempt)
var scores = [{
maxScore: "100",
obtainedScore: "79",
passed: "pass",
subject: "Maths"
}, {
maxScore: "100",
obtainedScore: "73",
passed: "pass",
subject: "Science"
}, {
maxScore: "100",
obtainedScore: "82",
passed: "pass",
subject: "English"
}]
function decoupler(arr, prop) {
return arr.map(function(item, index) {
return parseInt(item[prop], 10);
});
}
var arr1 = decoupler(scores, "maxScore");
var arr2 = decoupler(scores, "obtainedScore");
console.log(arr1);
console.log(arr2);
Edit: Added radix parameter for parseInt() based on comment by jfriend00.
what about mapping a projection?
var maxScores = scores.map(score => parseInt(score.maxScore, 10))
var obtainedScores = scores.map(score => parseInt(score.obtainedScore, 10))
I am not 100% sure what you want the output to be but :
i want obtainedScore and maxScore should be taken out from these
objects and place them in two different arrays
var arrScore = [],
arrMax = [];
scores.forEach(i => {
arrScore.push(!isNaN(parseInt(i.obtainedScore)) ? parseInt(i.obtainedScore) : 0);
arrMax.push(!isNaN(parseInt(i.maxScore)) ? parseInt(i.maxScore) : 0);
});
Basically this creates two arrays arrScore which will contain each individual score value and arrMax which contains an array of the max scores.
Using the forEach function we iterate the array and push the values into their respective arrays. Note for this we are also ensuring that the type is a valid integer.
scores = [
{
maxScore:"100",
obtainedScore:"79",
passed:"pass",
subject:"Maths"
},
{
maxScore:"100",
obtainedScore:"73",
passed:"pass",
subject:"Science"
},
{
maxScore:"100",
obtainedScore:"82",
passed:"pass",
subject:"English"
}
];
maxScoreArray = new Array();
obtainedScoreArray = new Array();
for (var i = scores.length - 1; i >= 0; i--) {
maxScoreArray.push(Number(scores[i].maxScore));
obtainedScoreArray.push(Number(scores[i].obtainedScore));
}
console.log(maxScoreArray);
console.log(obtainedScoreArray);
How do I push an object into an specified array that only updates that array? My code pushes an object and updates all arrays, not just the specified one.
Here is the structure of the data:
{
"d": {
"results": [
{
"Id": 1,
"cost": "3",
"item": "Project 1",
"fiscalyear": "2014",
"reportmonth": "July"
}
]
}
}
Here is a sample of the desired, wanted results:
{
"Project 1": [
{
"date": "31-Jul-14",
"rating": "3"
},
{
"date": "31-Aug-14",
"rating": "4"
}
],
"Project 2": [
{
"date": "31-Jul-14",
"rating": "2"
}
]
}
This is my attempt:
var results = data.d.results;
var date;
var projectObj = {},
projectValues = {},
project = '';
var cost = '',
costStatus = '';
for (var i = 0, m = results.length; i < m; ++i) {
project = results[i]['item'];
if (!projectObj.hasOwnProperty(project)) {
projectObj[project] = [];
}
// use Moment to get and format date
date = moment(new Date(results[i]['reportmonth'] + ' 1,' + results[i]['fiscalyear'])).endOf('month').format('DD-MMM-YYYY');
// get cost for each unique project
costStatus = results[i]['cost'];
if (costStatus == null || costStatus == 'N/A') {
cost = 'N/A';
}
else {
cost = costStatus;
}
projectValues['rating'] = cost;
projectValues['date'] = date;
projectObj[project].push(projectValues);
}
Here is a Fiddle with the undesired, unwanted results:
https://jsfiddle.net/yh2134jn/4/
What am I doing wrong?
That is because You do not empty it new iteration. Try this:
for (var i = 0, m = results.length; i < m; ++i) {
projectValues = {};
project = results[i]['item'];
....
}
Trying to push the values into temp Array, from the existing array object. Here am validating whether the values are null or not in my existing object and then pushing it into temp Array.
But currently this is output I am getting : ["0","abc"]
Expected output should be [{"0":"abc"},{"1":"def"}]
Once the values are pushed into the temp array, I need to bind it to my html list.
This is what have tried.
JS:
var tempArray = [];
var json = [
{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}
]
for (var i=0;i<json.length;i++){
if(json[i].itemId!=""&&json[i].prodTitle!="")
tempArray.itemId = json[i].itemId;
tempArray.prodTitle = json[i].prodTitle;
tempArray.push(tempArray.itemId,tempArray.prodTitle);
}
console.log(tempArray);
Demo URL
You have many mistakes, here's right one
for (var i=0; i<json.length; i++){
if(json[i].itemId && json[i].prodTitle) {
tempArray.push(json[i]);
}
}
Your mistakes
for (var i=0;i<json.length;i++){
if(json[i].itemId!=""&&json[i].prodTitle!="") // <-- mistake, braces are needed, because you have 3 lines below
tempArray.itemId = json[i].itemId; // <-- you are adding property to array
tempArray.prodTitle = json[i].prodTitle; // <-- still adding
tempArray.push(tempArray.itemId,tempArray.prodTitle); //<-- pushing strings, not valid object, use like --> {key: value}
}
Another option using Array.filter Also makes it chain-able. However a for loop will be faster, depends if the chain-ability is something you require, i find it quite powerful at times.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var json = [
{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}
];
var tempArray = json.filter(function (item) {
return (isDefined(item.itemId) && isDefined(item.prodTitle));
});
function isDefined (o) {
return o !== undefined && o !== null && o !== '';
}
console.log(tempArray);
http://jsfiddle.net/zgg79wfa/1/
You can achieve this without jQuery by using the .filter() method:
var json = [{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}];
console.log( json );
var tempArray = json.filter( function( el ) {
return el.itemId && el.prodTitle;
});
console.log( tempArray );
I have two js arrays already, say: names and values (with the same length), now I would like to construct a json object in certain format? For example:
names = ["label1","label2","label3"];
values = [[[0,1],[1,9],[2,10]],[[0,89],[1,91],[2,1]],[[0,1],[1,9],[2,10]]];
I would like to have a json array data_spec in this format:
[{
label:"label1",
data:[[0,1],[1,9],[2,10]]
},
{
label:"label2",
data:[[0,89],[1,91],[2,1]]
},
{
label:"label3",
data:[[0,1],[1,9],[2,10]]
}]
Could anyone tell one how? Thanks a lot!
For a bit of variety and a check,
var data_spec = [];
if (names.length != values.length) {
// panic, throw an exception, log an error or just return an empty array
} else {
for (var i=0, name; name = names[i]; i++) { // assuming a non-sparse array
data_spec[i] = {
label : name,
data : values[i]
};
}
}
That is, non-sparse and not containing anything else that would evaluate to false.
If your framework has an each function added to Array and you don't care about performance,
var data_spec = [];
names.each(function(name) {
data_spec.push({ label : name, data : values[names.indexOf(name)] });
});
If your framework is a clean one like Dojo and puts it somewhere else (ex is Dojo),
var data_spec = [];
dojo.forEach(names, function(name) {
data_spec.push({ label : name, data : values[names.indexOf(name)] });
});
If your framework has an each function that returns an Array of identical length with the results of every operation at their expected position,
var data_spec = arrayOfResultsEach(names, function(name) {
return { label : name, data : values[names.indexOf(name)] };
});
These are just for illustration, indexOf inside loops of arbitrary length is a major code smell.
Just use a loop (make sure the two arrays are of same length)
result = [];
for(var i=0, len=names.length; i < len; i++) {
result.push({label: names[i], data: values[i]});
}
var myArray =
[{
"label": "label1",
"data" :
{
"0": "1",
"1": "9",
"2": "10"
}
},
{
"label": "label2",
"data" :
{
"0": "89",
"1": "91",
"2": "1"
}
},
{
"label": "label3",
"data" :
{
"0": "1",
"1": "9",
"2": "10"
}
}];
alert(myArray[0].data[2]);