AngularJS - How to append json to another json object? - javascript

So I've to different objects, getting data from different sources. I need to convert them into a single object so that I can ng-repeat them.
object1 = {
"key1":"value one",
"key2":"value two"
}
object2 = {
"key1":"value three",
"key2":"value four"
}
What I need is
object3 = [{
"key1":"value one",
"key2":"value two"},
{
"key1":"value one",
"key2":"value two"}
}];
I tried angular.merge but it only works if the keys are different. In my case, keys are gonna be the same, only data is gonna change.
Can anyone help append object1 to object2 to create something like object3 which is object1+object2.
I tried converting them to json string & concatenating them but it didn't work.
Array contact function is not working either.

This is just vanilla javascript. You want to make an array of from the objects.
var object1 = {
"key1": "value one",
"key2": "value two"
}
var object2 = {
"key1": "value three",
"key2": "value four"
}
var object3 = []; // empty array
// add the other objects to the array
object3.push(object1);
object3.push(object2);
if your objects are already arrays and you just want to concatenate them, you can use the concat function on arrays.
var object1 = [{
key: 'abc',
value: 1
}];
var object2 = [{
key: 'cbd',
value: 2
}];
// use the concat function to concatenate the arrays
var object3 = object1.concat(object2);
You can find more about arrays by reading the documentation found here.
If your objects are firebaseArray objects they have their own API. More can be found here.

Related

Jquery Object and Array implementation

I have an Object
let data = {
a: 1,
b: 2,
c: {
abc: "ak",
bcd: "gh",
cfv: "ht"
}
}
then I have variables which I need to show with these object value
let abc = "first 1", bcd="sec2", cfv="third3" , def="fourth 4", tdf = "fifth 5";
Now the Object will come in API call it can be any of these variable.
How can I match the variable name with the object data.c.(object key) and concatinate their value.
for example the output should be
As we have (abc, bcd, cfv) as our object key then the output would be
first 1ak ==> that is the value of (abc + data.c["abc"])
sec2gh ==> that is the value of (bcd + data.c["bcd"])
third3ht ==> that is the value of (cfv + data.c["cfv"])
I tried using Object.keys() method so from this method we will get the object keys in array then how can I match with the variable name -
Object.keys(data.c);
==> ["abc", "bcd", "cfv"] (After this how can I proceed to match the variable and show their values?)
Shall I loop throught the object that (data.c)?
Please help me giving some ideas to achieve this implementation.
thank you
If it's possible for you to amend the format of your abc, bcd etc. variables to be the properties in an object, then this problem becomes trivial. You can use flatMap() to create a new array of the output values by linking the properties of the two target objects, like this:
let values = {
abc: "first 1",
bcd: "sec2",
cfv: "third3",
def: "fourth 4",
tdf: "fifth 5"
}
let data = {
a: 1,
b: 2,
c: {
abc: "ak",
bcd: "gh",
cfv: "ht"
}
}
let output = Object.keys(values).flatMap(k => data.c.hasOwnProperty(k) ? values[k] + data.c[k] : []);
console.log(output);

Using the spread operator on an array with objects

I got a Javascript object which looks like this:
{
key1: {
itemId: "someId",
myValue: "value"
},
key2: {
itemId: "someId2",
myValue: "value2"
}
}
I also got an array to which I push items like this:
myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items
I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:
{
key1: {
itemId: "someId",
myValue: "value"
},
key2: {
itemId: "someId2",
myValue: "value2"
},
key3: { //the object that was added },
key4: { //the object that was added }
}
I tried doing it with the spread operator:
return {...object, ...myArr}
But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).
How do I concatenate the object and the array the way I want?
rather my myArray create myObject.
myObject = {}
myObject[item.itemId] = anotherDefinedObject;
Then
return {...object, ...myObject}
const obj = {key1: 1};
const myArr = [{key2: 2}];
myArr.forEach(val => Object.assign(obj, val));
console.log(obj); // {key1: 1, key2: 2}
What you're looking to achieve here is not possible with the spread operator; it's working exactly as intended and the functionality cannot be changed as JS doesn't allow operator overloading. Your best bet is to loop through myArr and add each item in the array to the object using your own code.
P.S. As the comments suggest, in the future you should really provide more examples of your input, the current output, and your intended output; it was quite difficult to follow without it.

How to parse JSON object into their designated types in Javascript?

When I make an API request, the API server returns me a JSON object. How do I parse the JSON object to their designated types in Javascript?
This is what is being returned to me:
{
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
So would like to parse the array, classes, the object, food, and the string student_name, and console log them.
You need to use JSON.parse() to do it:
var myData = {
"student_name": "Joshua",
"classes": [
"A1",
"A2",
"A3",
]
"food": {
"size": "slice",
"type": "pepperoni",
}
}
var myObject = JSON.parse(myData);
console.log(myObject.student_name); //Output: Joshua
console.dir(myObject) //to see your object in console.
display a single element:
console.log(myData.classes[0]);
display all elements of an array:
var arr = myData.classes;
for(var i in arr)
{
console.log(arr[i]);
}
For more information:
About JSON.parse()
JSON.Parse() Examples
JSON is the JavaScript Object Notation, which means JSON snippets already represent JavaScript objects. You just have to parse them using:
var myObject = JSON.parse(json);
And then you can access:
var myArray = myObject.classes; //should give you an array
console.log(myArray[0]); //should print "A1"
var myFood = myObject.food //should give you a food object with size and type properties
console.log(myFood.size); //should print "slice"

fastest way to go through JSON object in Javascript

I have an array of JSON-like object[Object,Object...] (I was calling it array of JSON object until I see this ) and I would like to go through each item in it. The JSON object has 3 values {name:"name",date:"2015-01-01",c:3} in it and I want to put each of them into a new array. Should I use a for item in JSONArary{item = ...} or for (i=0,i<len,i++){array[i] = ....} or should I JSONArray.pop()? Which one is faster and why? What if I want to reverse the array? Do reversing cost a lot?
for (i=0,i<len,i++){array[i] = ....} should be faster than for item in JSONArary{item = ...} because the later will traverse all enumerable properties on this object, while some of these properties are unnecessary.
When you want to iterate over just the indexed properties of an array, the only guaranteed way to keep things semantically consistent is to use an integer index.
For your reference: Why is using "for...in" with array iteration a bad idea?
Even Google make the JavaScript coding style guide as:
for-in loop: Only for iterating over keys in an object/map/hash
I have a faster way, use $.map:
var oldArray = [{
name: "name1",
date: "2015-01-01",
c: 3
}, {
name: "name2",
date: "2015-01-01",
c: 3
}, {
name: "name3",
date: "2015-01-01",
c: 3
}];
var newArray = $.map(oldArray, function (item) {
return {
FullName: item.name,
RegisterDate: item.date
};
});
alert(JSON.stringify(newArray));
Hope this help.

Adding value to top of the JSON

I have JSON data
var json = {"options": {
"key1": "value2",
"key2": "value2",
"key3": "value3",
}
}
And I want to add one more key with value to it using JavaScript, but I want it to be on the top like this:
var json = {"options": {
"new_key": "new_value",
"key1": "value2",
"key2": "value2",
"key3": "value3",
}
}
How can I do it?
Objects do not guarantee property order in JavaScript, but arrays do. If the order really matters and you are allowed to change your JSON structure, I'd suggest to use an array instead to organize your data.
var json = {
"options": [
{"key": "key1", "value": "value1"},
{"key": "key2", "value": "value2"},
{"key": "key3", "value": "value3"}
]
};
Using this, you could push an element to the start of the array using the unshift method.
json.options.unshift({"key": "new_key", "value": "new_value"});
Although it is not required by any of the ECMAScript specs, nonetheless most implementations do retain the original order of keys in Objects, with the exception of keys with numeric values. You can see a lengthy discussion about the Chrome's implementation here: http://code.google.com/p/v8/issues/detail?id=164
If you want to utilize this, you will need to create a new Object:
var newOpts = {};
newOpts["new_key"] = "new_value";
for (var k in json.options) {
newOpts[k] = json.options[k];
}
json.options = newOpts;
However if you do actually turn your object into a JSON string, and send it to someone else, there is no guarantee that they will preserve the order when they parse the string back into an Object.
I was surprised to discover the widely used Express library for NodeJS actually relies on this behaviour for its format method.
JSON Objects have no order.
If order is important to you, consideer creating options as an array, then you can iterate and adding items in a specific order:
var json = {"options": [
{key: "new_key", value: "new_value"},
{key: "key1", value: "value2"},
{key: "key2", value: "value2"},
{key: "key3", value: "value3"},
]}
You can extend the object in the following way using vanilla JavaScript but again this won't set the order as others have noted.
extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
var json = {
"options": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
};
extend(json.options, {"new_key": "new_value"});
You could use the extend function the ordering of the objects would determine which parameters would be written first, but as stated by DanFromGermany there aren't many real-life cases where the order is relevant.

Categories