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 += ", ";
}
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}
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;
});
There are couple of different solutions to achieve this:
1 - Native javascript for-in loop:
const result = {};
let key;
for (key in obj1) {
if(obj1.hasOwnProperty(key)){
result[key] = obj1[key];
}
}
for (key in obj2) {
if(obj2.hasOwnProperty(key)){
result[key] = obj2[key];
}
}
2 - Object.keys():
const result = {};
Object.keys(obj1)
.forEach(key => result[key] = obj1[key]);
Object.keys(obj2)
.forEach(key => result[key] = obj2[key]);
3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)
const result = Object.assign({}, obj1, obj2);
4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):
Defined in several sections of the specification: Array Initializer, Argument Lists
Using this new syntax you could join/merge different objects into one object like this:
const result = {
...obj1,
...obj2,
};
5 - jQuery.extend(target, obj1, obj2):
Merge the contents of two or more objects together into the first object.
const target = {};
$.extend(target, obj1, obj2);
6 - jQuery.extend(true, target, obj1, obj2):
Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.
const target = {};
$.extend(true, target, obj1, obj2);
7 - Lodash _.assignIn(object, [sources]): also named as _.extend:
const result = {};
_.assignIn(result, obj1, obj2);
8 - Lodash _.merge(object, [sources]):
const result = _.merge(obj1, obj2);
There are a couple of important differences between lodash's merge function and Object.assign:
1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:
_.isEqual(_.merge({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
}), {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // true
BUT:
const result = Object.assign({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
});
_.isEqual(result, {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // false
// AND
_.isEqual(result, {
x: {
y: {
key2: 'value2',
},
},
}); // true
2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:
_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false
BUT:
_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true
Update 1:
When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype.
To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.
Update 2:
I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.
Update 3:
I added the difference between Object.assign and _.merge.
WORKING FIDDLE
Simplest Way with Jquery -
var finalObj = $.extend(obj1, obj2);
Without Jquery -
var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];
why don't you do it like this?
var x = {
order: {
currency: 'eur',
order_items: []
}
};
for (var i = 0; i < 10; i++) {
var newObject = {
i: i,
Text: 'Some Text'
};
x.order.order_items.push(newObject);
}
var str = JSON.stringify(x);
look at this fiddle: http://jsfiddle.net/9V6Vb/
Here is the generated JSON:
{
"order": {
"currency": "eur",
"order_items": [{
"i": 0,
"Text": "Some Text"},
{
"i": 1,
"Text": "Some Text"},
{
"i": 2,
"Text": "Some Text"},
{
"i": 3,
"Text": "Some Text"},
{
"i": 4,
"Text": "Some Text"},
{
"i": 5,
"Text": "Some Text"},
{
"i": 6,
"Text": "Some Text"},
{
"i": 7,
"Text": "Some Text"},
{
"i": 8,
"Text": "Some Text"},
{
"i": 9,
"Text": "Some Text"}]
}
}
As Koen say it, you can make an object with first property is order and stringify all object in one time.
var myOrder = {
order: {
currency: 'eur',
order_items: [
{
id: 3,
quantity: 1
},
{
id: 67,
quantity: 1
}
]
}
}
console.log("currency : " + myOrder.order.currency);
for (var i in myOrder.order.order_items) {
console.log("items number " + i);
console.log("items id" + myOrder.order.order_items[i].id);
console.log("items quantity" + myOrder.order.order_items[i].quantity);
}
var myString = JSON.stringify(myOrder);
console.log(myString);
but I think you should make "order" your object direcly
Regards,
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.
When you do
"interests = " + arr
the toString method in that array object will be invoked. Quoting the Array.prototype.toString documentation,
The
Arrayobject overrides thetoStringmethod ofObject. ForArrayobjects, thetoStringmethod joins the array and returns one string containing each array element separated by commas. For example, the following code creates an array and usestoStringto convert the array to a string.var monthNames = ['Jan', 'Feb', 'Mar', 'Apr']; var myVar = monthNames.toString(); // assigns 'Jan,Feb,Mar,Apr' to myVar.
To fix your test case, you need to convert the Array manually, like this
str += "interests = [" + monthNames.map(function(currentString) {
return "'" + currentString + "'";
}).join(", ") + "]";
When you join an array to a string, Javascript will automatically concatenate out the values inside of the array.
For example:
var str = 'my string'+[ 'my', 'arr' ];
Will produce:
"my stringmy,arr"
You must serialise the array using JSON.stringify (or similar). For example:
var str = 'my string';
str+= JSON.stringify( [ 'my', 'arr' ]);
Will produce:
"my string["my","arr"]"
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)