This looks like a job for $.map!
var data = {
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
}
var cats = $.map(data.category, function(v){
return v.name;
}).join(', ');
Answer from gen_Eric on Stack OverflowThis looks like a job for $.map!
var data = {
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
}
var cats = $.map(data.category, function(v){
return v.name;
}).join(', ');
var text = "";
for(var i=0; category.length; i++)
{
text += category[i].name;
if(i!=category.length-1)
text += ", ";
}
If i understood correctly, you can do the following:
var json= {"Title":"Movie1","Year":"2013"};
var result="";
for( key in json){
result+= json[key];
}
You don't have to know the number of properties or it's names before hand. This should work for simple scenarios.
Demo try this,
var json= {"Title":"Movie1","Year":"2013"};
var append="";
$.each(json,function(key,value){
append+=value;
});
Based on your description in the comments, you'd simply do an array concat():
var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
console.log(jsonArray1)
// [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}, {'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
The actual way is using JS Object.assign.
Object.assign(target, ...sources)
MDN Link
There is another object spread operator which is proposed for ES7 and can be used with Babel plugins.
Obj = {...sourceObj1, ...sourceObj2}
Alasql JavaScript SQL library does exactly what you need in one line:
<script src="alasql.min.js"></script>
<script>
var data = { COLORS: [[1,"red"],[2,"yellow"],[3,"orange"]],
FRUITS: [[1,"apple"],[2,"banana"],[3,"orange"]]};
data.NEW_FRUITS = alasql('SELECT MATRIX COLORS.[0], COLORS.[1], FRUITS.[1] AS [2] \
FROM ? AS COLORS JOIN ? AS FRUITS ON COLORS.[0] = FRUITS.[0]',
[data.COLORS, data.FRUITS]);
</script>
You can play with this example in jsFiddle.
This is a SQL expression, where:
- SELECT - select operator
- MATRIX - modifier, whci converts resultset from array of objects to array of arrays
- COLORS.[0] - first column of COLORS array, etc.
- FRUITS.1 AS 2 - the second column of array FRUITS will be stored as third column in resulting recordset
- FROM ? AS COLORS - data array from parameters named COLORS in SQL statement
- JOIN ? ON ... - join
- [data.COLORS, data.FRUITS] - parameters with data arrays
The fact that there will be thousands of inputs and the keys are not necessarily ordered means your best bet (at least for large objects) is to sort by key first. For objects of size less than about 5 or so, a brute-force n^2 approach should suffice.
Then you can write out the result by walking through the two arrays in parallel, appending new "records" to your output as you go. This sort-then-merge idea is a relatively powerful one and is used frequently. If you do not want to sort first, you can add elements to a priority queue, merging as you go. The sort-then-merge approach is conceptually simpler to code perhaps; if performance matters you should do some profiling.
For colors-without-fruits and fruits-without-colors, I assume writing null for the missing value is sufficient. If the same key appears more than once in either color or fruit, you can either choose one arbitrarily, or throw an exception.
ADDENDUM I did a fiddle as well: http://jsfiddle.net/LuLMz/. It makes no assumptions on the order of the keys nor any assumptions on the relative lengths of the arrays. The only assumptions are the names of the fields and the fact that each subarray has two elements.
Note JSON stands for JavaScript Object Notation. JSON is always a string. It is a string representation of your encoded data. There is no such thing as "a JSON Object".
Don't attempt to write JSON by joining strings and other values together. Instead build an object and pass it to JSON.stringify -
const dept = "sci"
const avg = 77.09
// make an object
const myobject = { courses_dept: dept, courses_average: avg }
// use JSON.stringify to encode myobject to JSON
const myjson = JSON.stringify(myobject)
console.log("encoded", myjson)
// test JSON.parse to decode the JSON and get the object back
console.log("decoded", JSON.parse(myjson))
encoded {"courses_dept":"sci","courses_average":77.09}
decoded {
"courses_dept": "sci",
"courses_average": 77.09
}
If you want to use strings:
var dept = "sci";
var avg = 77.09;
let a = `{"courses_dept": "${dept}", "courses_averge": ${avg} }`;
This assumes that dept is a string. If you don't know this in advance, wrap each variable with JSON.stringify:
let b = `{"courses_dept": ${JSON.stringify(dept)}
,"courses_averge": ${JSON.stringify(avg)}}`;
Notice that the string uses backticks ` instead of regular quotes. This allows you to do string interpolation. You can use + if you want to do straight up concatenation.
You can also just do a regular object:
let c = {"courses_dept": dept, "courses_averge": avg}
JSON.stringify(c)