JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
Answer from Paul S. on Stack OverflowJSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
As you asked, here's how to do it:
- Mapping the array to an object
- Converting the object to JSON
let array = [{
Field: 'Key',
Value: '7'
},
{
Field: 'City',
Value: 'Some City'
},
{
Field: 'Description',
Value: 'Some Description'
}
];
// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);
// #2 Converting the object to JSON...
let json = JSON.stringify(obj);
console.log(json);
Bonus (ES6 + reduce):
const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
you can try the below approach . I have used spread operator(ES6) and Object.assign to create the object ,then converted it into json string.
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
let obj = Object.assign(...SampleData.map( x => Object.values(x)).map(y => ({[y[0]]: y[1]})));
console.log(obj);
//{ Key: "7", City: "Some City", Description: "Some Description" }
console.log(JSON.stringify(obj));
Observation
- If there is a single object and you want to push whole object into an array then no need to iterate the object.
Try this :
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
data.push(feed);
console.log(data);
Instead of :
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
for(var i in my_json) {
data.push(my_json[i]);
}
console.log(data);
You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
data.push(my_json);
//["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
});
console.log(data);
Hi there!
I'm new to JavaScript and was learning about arrays today and saw that the instructor only added an array to another array. Is it possible to add something that is not an array into an array? Iyes, how can I do that?
Thanks in advance!
Use the Array.prototype.push method to append values to the end of an array:
Copy// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You can use the push() function to append more than one value to an array in a single call:
Copy// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Note that the push() method returns the updated length of the array.
Update
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):
Copyvar arr = [
"apple",
"banana",
"cherry"
];
// Do not forget to assign the result as, unlike push, concat does not change the existing array
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Update
Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.
Copyvar arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
It also supports appending multiple values at once just like push.
Update
Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended or prepended, compliant with the spirit of functional programming.
Copyconst arr1 = [
"Hi",
"Hello",
"Bonjour",
];
const arr2 = [
"Ciao",
"Hej",
"Merhaba",
];
const newArr1 = [
...arr1,
"Salut",
];
const newArr2 = [
"Salut",
...arr2,
];
const newArr3 = [
...arr1,
...arr2,
];
console.log(newArr1, newArr2, newArr3);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():
Copyvar ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar1);
alert(ar2);
alert(ar3);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
The concat does not affect ar1 and ar2 unless reassigned, for example:
Copyvar ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
ar1 = ar1.concat(ar2);
alert(ar1);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
There is a lot of great information on JavaScript Reference.
I’m working on a chat client and server to learn about API’s and now I need to write the messages submitted by users into the master chat log (a json file with a messages array inside of it). I have been searching for different approaches and they all error out somehow. I’m using node and express for routing if that helps.
tldr; how should one append an object to an array inside a json file using node.
edit: I’ve taken carcigenocate’s advice. I open the file, make the changes in memory, then write to the file and reload it to reflect changes. I am still open to improvements on this design!
I have a json array of Objects and need to pick a corresponding object in that array according to some calculations.
My json have a following structure: {"OD": number, "SCH" {"SCH40": number, "SCH80": number}}
I need to do some math with OD and SCH numbers, compare it with an outside number and find corresponding value for OD key.
I can get a new array (of numbers I compare the outside number with):
this.Pipeareas = this.Pipesizes.map (x => Math.pow((x.OD - 2 * x.SCH[this.selectedSCH])/2000,2) * Math.PI);
How to merge existing and new arrays?
I tried (this add extra existing array and new object to new array (not key:value pair))
this.Pipeareas = {...this.Pipesizes, Area: this.Pipesizes.map (x => Math.pow((x.OD - 2 * x.SCH[this.selectedSCH])/2000,2) * Math.PI) }
and (this adds new key "Area" to each object but the value is full array, not corresponding numbers from new array)
this.Pipesizes.map (x => x.Area = this.Pipesizes.map (x => Math.pow((x.OD - 2 * x.SCH[this.selectedSCH])/2000,2) * Math.PI))
The result should be like:
return this.Pipeareas.find(x => x >= this.OutsideNumber);