I'm getting a JSON using
$.getJSON("http://localhost:8080/test_json/", function(data) {
});
Output looks like this.
{"items":[{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}]}
After some trimming
data = JSON.stringify(data);
data = data.substring(9);
data = data.substring(0, data.length - 1);
data = data.replace(/[{}]/g, " ");
console.log(data);
It looks like this
["1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7]
I would like to "deconstruct" (?) this as to remove all keys so that only values remain.
[1 ,2 ,3 , 4 , 5 , 6 ,7]
I'm going to use this to draw charts. So for exampel that could be my data that I'm going to pass to my chart library.
Please don't start "trimming" your JSON like that. Just parse it and process it like any other object.
var json = '{"items":[{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}]}';
Parse your JSON to a JS object (tho I note that you're using jQuery to get the data so this will be parsed already, so you can skip this step):
var obj = JSON.parse(json);
Grab the first element of items (an array) which is an another object:
var items = obj.items[0];
Grab the item keys with Object.keys() and use that array to return the values with map.
var vals = Object.keys(items).map(function (el) {
return items[el];
}); // [ 1, 2, 3, 4, 5, 6, 7 ]
DEMO
EDIT
So now you have some new data:
var json = '{"items":[{"sum":188700.75},{"sum":633927.98},{"sum":7000},{"sum":65169.26},{"sum":17114.67},{"sum":252340.96},{"sum":1073246.73}]}'
The following JS will grab the value of sum from each object:
var items = obj.items;
var vals = items.map(function (el) {
return el.sum;
});
Output
[ 188700.75, 633927.98, 7000, 65169.26, 17114.67, 252340.96, 1073246.73 ]
DEMO
You have json data why need stringify it ?
var input = data.items[0]
var arr = $.map(input,function(v){
return v;
});
First, if you want to extract the values, you can do it by accessing it like this:
var obj = data.items[0];
Your variable obj will look like this:
{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}
Then I guess you will have to iterate on this object to make it an array:
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
The variable arr will then contain the elements you wish.
DEMO
A different approach from what have been told you.
You don't need to trim the data.
var json = JSON.parse(data);
var items = json.items[0];
And you don't need to remove keys, you can send the values into another array.
var listOfItems = [];
for(var key in items)
listOfItems.push(items[key]);
Related
I want to push my object without a key in my javascript array. Right now the issue is I psuh my object in the array, but I add extra key 0,1,2 ... I don't want that key. Is there any solution for that? Here I add the code that I implemented.
let newArr = [];
let myId = data['id'];
var key = myId;
var obj = {};
myobj[key] = {
data: "testdata"
};
newArr.push(myobj);
The above code generates output like below. I don't want that 0 key in my array
0: {
260: {
data: 'testdata'
},
}
It's hard to tell what you're wanting, but I expect you don't want to be using an array here at all? You just want a single object that contains all of your key-value pairs?
e.g. something like this:
const data = { id: 1234 };
let myId = data['id'];
var key = myId;
var myobj = {};
myobj[key] = {
data: "testdata"
};
console.log(myobj);
// You can then add more data
myobj[2345] = {
data: "more test data"
};
console.log(myobj);
// Example Property Access
console.log(myobj[2345])
Try this
newArr.push(...myobj);
I hava a json response like [{0},{1},{2}..] and each index contains object data. I also have an object like a{} which also contains object data.What I want is to add the object a "inside"(at the end) the each index like [{0..a},{1..a},{2a}].
Parse the json response using JSON.parse then iterate over it and add the object inside each object
var resp = '[{"data":"1"},{"data":"2"},{"data":"3"},{"data":"4"}]';
var arr = JSON.parse(resp);
console.log(arr);
var a = {
data: 5
};
arr.forEach(function(element,i) {
arr[i].a = a;
});
console.log(arr)
So assuming your json response is in some variable (let's say its called jsonResponse) and a is an Object you can do:
jsonResponse.push(a)
Which will add the a object to the end of the jsonResponse array.
This assumes that jsonResponse is an array, if it is a string you may have to do something like:
let jsonResponse = JSON.parse(responsestring)
Your question is not totally clear, but sounds like you want to look at array.map.
For example:
let arr = [{x:1,y:2},{x:3,y:4}];
const foo = arr.map(obj=>{obj.z=42; return obj})
console.log("GOT:", foo);
to combine two json objects:
function combineObj(ob1, ob2) {
return Object.fromEntries(Object.entries(ob1).concat(Object.entries(ob2)));
}
var a = [{b:1},{q:3},{s:2}],
b = {a:2};
var result = a.map(x=>combineObj(x,b));
console.log(result);
From what I understand you want to add Object A to every Object in your JSON response?
If so try:
var jsonResponse = [{a: 1}, {a: 1}, {a: 1}]
var objToAppend = {b:2}
for(var objectInJsonResponse of jsonResponse){
objectInJsonResponse.appendedObject = objToAppend;
}
This will result in:
console.log(jsonResponse)
[{a:1,appendedObject:{b:2}},{a:1,appendedObject:{b:2}},{a:1,appendedObject:{b:2}}]
Of course you can change the name of appendedObject to whatever you want the key to be.
The strings that are coming from source is coming in fragmented JSON object in JSON object.I want to convert this JSON structure to a another simple JSON structure:
{
"nestA":{
"a":"link",
"b":2711
},
"nestB":{
"a":"img",
"b":4165
}
}
could it changed to be like
{
"key":"nestA"
"a":"link"
"b":711
},
{
"key":"nestB"
"a":"img"
"b":165
}
//convert json string into an object
var json = '{"nestA":{"a":"link","b":2711},"nestB":{"a":"img","b":4165}}'
var sourceObject = JSON.parse(json);
//get a list of the object keys
var keys = Object.keys(sourceObject);
//create a new array to hold our output
var array = [];
//loop through our keys adding them to our array in the format we want
keys.forEach(function(key){
var nest = sourceObject[key];
nest.key = key;
array.push(nest);
});
//convert our array back to json
var result = JSON.stringify(array);
console.log(result);
var json = [{
"nestA":{
"a":"link",
"b":2711
},
"nestB":{
"a":"img",
"b":4165
}
}];
var arr = [];
json.forEach(function(v) {
Object.keys(v).forEach(c => arr.push(v[c]));
arr.forEach((b, x) => b['key'] = Object.keys(v)[x]);
});
console.log(arr);
Working with JSON it's best to parse it first, modify it and then turn it back into JSON:
var orgObj = JSON.parse(orgJSON);
var newArr = [];
for( var key in orgObj){
var temp = { key: key };
Object.assign( temp, orgObj[key]);
newArr.push(temp);
}
var newJSON = JSON.stringify(newArr);
Assuming an array was what you were going for. Please clean up your desired JSON.
Without using es6 the for loop could be:
for( var key in orgObj){
orgObj[key].key = key;
newArr.push( orgObj[key] );
}
but orgObj would get modified.
I have an Object array that looks like the following:
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
And I want to convert it to look like this:
var newArray = [
1, 2, 3
]
So it's basically taking the object array, extracting the id's out of the objects, and creating a new array that contains the id's that were extracted. Is there a way to do this in one line? Even better if a new array doesn't have to get created and array is just updated.
var test ="sai";
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
console.log(array.map(function(obj){return obj.id}))
iterate the array using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );
array.map(function (item) {
return item["id"];
}
If you'd like to have anew instance of the mapped array:
var newarray = [];
array.forEach(function (item) {
newarray.push(item["id"]);
}
array.map(function(element) {return element.id})
OP Requirement: better if array is just updated
array = array.map(function(element) {return element.id})
hi I am using angularjs and when I print this line
console.log(JSON.stringify($scope.data));
I am getting below data in my browser console
"FirstName,LastName,CII Number,Document Path\r\nJohn1,Rambo1,bulktest1,D:/MyDOJ/input_2/1000.pdf\r\nJohn2,Rambo2,bulktest2,D:/MyDOJ/input_2/1020.pdf\r\nJohn3,Rambo3,bulktest3,D:/MyDOJ/input_2/1010.pdf\r\nJohn4,Rambo4,bulktest4,D:/MyDOJ/input_2/5010.pdf\r\n"
I want to form this data as JSON object as below
[{ "FirstName":"John1" , "LastName":"Rambo1" ...},
{ "FirstName":"John2" , "LastName":"Rambo2" ...},
{ "FirstName":"John3" , "LastName":"Rambo3" ...}] etc
please suggest me how to do this.
Your $scope.data is a string containing comma separated values, you have to first convert it to an object.
function parseCSV(csv) {
var rows = csv.split('\r\n'), //Split the CSV into rows
keys = rows.shift().split(','), //First row contains keys, so we take that out of rows
out = []; //output array
rows.forEach(function (row) {
var obj = {}; //object for our row
row.split(',').forEach(function (value, index) {
obj[keys[index]] = value; //use the key in keys and set the value
});
out.push(obj); //add object to out
});
return out;
}
var object = parseCSV($scope.data);
console.log('object', object);
console.log('json string', JSON.stringify(object));
Working jsFiddle