I have an array of objects. if i do a console.log, i can see these array of objects.
[Object, Object, Object, Object,Object]
[0-4]
0:Object
Name: Nikhil
User_ID:123
admin:true
read:false
write:false
1:Object
Name:andy
User_ID:124
admin:false
read:true
write:false
2:Object
Name:Nik
User_ID:125
admin:false
read:false
write:true
3:Object
Name:ranea
User_ID:126
admin:false
read:false
write:true
4:Object
Name:isha
User_ID:127
admin:false
read:true
write:false
Now, if i do JSON.stringify, i get this output.
[{"Name":"Nikhil","User_ID":"123","admin":true,"read":false,"write":false},
{"Name":"andy","User_ID":"124","admin":false,"read":true,"write":false},
{"Name":"Nik","User_ID":"125","admin":false,"read":false,"write":true},
{"Name":"ranea","User_ID":"126","admin":false,"read":false,"write":true},
{"Name":"isha","User_ID":"127","admin":false,"read":true,"write":false}]
Instead of doing stringify to all the parameters, I want to only do it to few. For e.g. I don't want to pass Name. I only want to pass User_ID since it is unique, and admin,read,write properties.
How can i create a new array of objects using loadash and then stringify the result. My final output after JSON.stringify should be like this
[{"User_ID":"123","admin":true,"read":false,"write":false},
{"User_ID":"124","admin":false,"read":true,"write":false},
{"User_ID":"125","admin":false,"read":false,"write":true},
{"User_ID":"126","admin":false,"read":false,"write":true},
{"User_ID":"127","admin":false,"read":true,"write":false}]
Using _.pick it should be:
var newArr = _.map(oldArray,
function(item) {
return _.pick(item, ['User_ID', 'admin', 'read', 'write']);
});
You could make use of the Array.map() function.
var obj = [ { "Name": "Christophe", "Age": 42, "foo": "bar" }, { "Name": "Blah", "Age": 42, "foo": "foo2" }]
var filtered = obj.map(function (element) {
return {
"Name": element.Name
}
});
After that, filtered contains your objects with only the keys you want to keep, and you can JSON.stringify it.
console.log(JSON.stringify(filtered));
// [ {"Name": "Christophe"}, {"Name": "Blah"} ]
You can use this little function to return
the new Array.
var arr = [{
Name: "Nikhil",
User_ID: "123",
admin: "true",
read: "false",
write: "false"
}, {
Name: "andy",
User_ID: "124",
admin: "false",
read: "true",
write: "false"
}];
function returnArr(array) {
var arrNew = arr;
for (let in arrNew) {
delete arrNew[let].Name;
}
return JSON.stringify(arrNew);
}
document.write(returnArr(arr)); // or console.log(returnArr(arr))
Related
I had this JSON:
"event": [
{
"timestamp": "2016-10-02T11:37:31.2300892-03:00",
"revenue": 120.0,
"transaction_id": "3409340",
"store_name": "BH Shopping",
"products": []
}
And this Object Array:
[ { name: 'Blue Shirt', price: 100 },
{ name: 'Nike Shoes', price: 150 } ]
How can I add the Object Array into the products Array inside the JSON using Javascript?
Please check this solution of adding objects to object property:
var jsonStr = '{"event": {"timestamp": "2016-10-02T11:37:31.2300892-03:00", "revenue": "120.0", "transaction_id": "3409340", "store_name": "BH Shopping", "products": []}}';
var obj = JSON.parse(jsonStr);
obj['event']['products'].push({"name":"Blue Shirt","price":"100"});
obj['event']['products'].push({"name":"Nike Shoes","price":"150"});
jsonStr = JSON.stringify(obj);
console.log(jsonStr);
From the look of it, event is a JSON Array on its own so to target the first one you will have to pict JSON Object at index 0.
var eventObject = event[0];
Now the products is an array and you can push staff into it by iterating over your Object Array
objectArray.forEach(function(object){
//the object is each array item
eventObject.products.push(object);
});
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"
I am having the below JSON object.
"Department": [
{
"depType": "Testing",
"name": "xyz",
"address":""
},
{
"deptype": "Developer",
"name": "abc"
}
]
I want to create another object based on the type of deptartment (depType). Something like this
"Testing":{
"name": "xyz",
"address":""
},
"Developer":{
"name": "abc"
}
With the help of Object.keys, I was able to get the keys
You had some Property-naming issues with camelCased "depType". Fix that.
Create a new copy of the desired object to manipulate using JSON.parse(JSON.stringify(orgObj))
Loop that object to find the desired Property "Department"
Since Department is an Array of Objects you need to loop that Array for(var i=0; i<dep.length; i++).
Than you'll need to match if that Array contains arrObj.hasOwnProperty( "depType" )
if successful you can than fill your new object with all the info newObj[arrObj.depType] = arrObj;
Since now, inside your new object there's also the good old "depType" property you can get rid of it using delete.
jsBin demo
var myjson = {
"Department": [
{
"depType": "Testing", // NOTE: "camelCase"
"name": "xyz",
"address":""
},
{
"depType": "Developer", // FIX: "camelCase" !!
"name": "abc"
}
]
};
function depTypify( orgObj ) {
var objCopy = JSON.parse(JSON.stringify(orgObj)); // Fresh copy
var newObj = {};
for(var prop in objCopy){
if(prop === "Department") {
var dep = objCopy[prop]; // get Department Array
for(var i=0; i<dep.length; i++) { // Loop array
var arrObj = dep[i]; // Explore Each Array Object
if(arrObj.hasOwnProperty( "depType" )) {
newObj[arrObj.depType] = arrObj;
delete arrObj.depType; // We don't need it any more
}
}
}
}
return newObj;
}
var myNewJson = depTypify( myjson );
if you do than console.log( myNewJson ) this is what you'll get:
[object Object] {
Developer: [object Object] {
name: "abc"
},
Testing: [object Object] {
address: "",
name: "xyz"
}
}
The nice thing is that your old json is still intact.
I got stuck trying to retrive array items. So here is the deal. I have a two dimentional array which has value and key so example of my data is:
[
Object { css="SS", title="Apple"},
Object { css="SS", title="Orange"},
Object { css="SS", title="Banana"}
]
I want to see if an object exists in the array above. And I have no idea why its not working, here is my code to find the object:
jQuery.inArray("Apple", fruits["title"]); //this returns -1 why?
Any ideas how to search two dimensional array?
This is not a 2D array, this is an array of objects, so this should work:
for (var i = 0; i < array.length; i++) {
console.log(array[i].title); //Log the title of each object.
if (array[i].title == "Apple") {
console.log("Found apple!");
}
}
Also, objects are key/val pairs, denoted by key : val, not key = val. Your array has syntax errors and shouldn't run.
To be pedantic, you have an array of objects, not a 2d array. Also your syntax for the object parameters is incorrect.
You can use filter() on the array to find the values:
var array = [
{ css: "SS", title: "Apple"},
{ css: "SS", title: "Orange"},
{ css: "SS", title: "Banana"}
];
var matches = array.filter(function (obj) { return obj.title == "Apple" });
if (matches.length) {
// Apple was in the array...
}
If you have an object like this
var peoples = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
Ignore what's below. Use the filter method!
peoples.filter(function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
You can search for people who have "dinner": "sushi" using a map
peoples.map(function (person) {
if (person.dinner == "sushi") {
return person
} else {
return null
}
}); // => [null, { "name": "john", "dinner": "sushi" }, null]
or a reduce
peoples.reduce(function (sushiPeople, person) {
if (person.dinner == "sushi") {
return sushiPeople.concat(person);
} else {
return sushiPeople
}
}, []); // => [{ "name": "john", "dinner": "sushi" }]
I'm sure you are able to generalize this to arbitrary keys and values!
fruits probably is a array, fruits["title"] therefor doesn't exist.
You might want to transform your data:
var fruitTitles = fruits.map(function(f) { return f.title; });
jQuery.inArray("Apple", fruitTitles);
From the jQuery docs:
jQuery.inArray( value, array [, fromIndex ] )
I've never used this method, but a quick guess:
var hasIt = jQuery.inArray({css:"SS",title:"Apple"}, myArray);
As the $.inArray() documentation explains, the first argument to the function is the value to search for. Your array does not have any elements that are equal to the string "Apple" that you have supplied in the first argument because none of your array elements are strings (they're all objects).
The second argument to $.inArray() is supposed to be the array itself, but (assuming fruits is the array you show) fruits["title"] is undefined because your array has no property called "title", only the objects in the array have that property.
Try this instead:
var index = $.inArray("Apple", $.map(fruits, function(el) { return el.title; }));
try this code
var fruits = [
{ css:"SS", title:"Apple"},
{ css:"SS", title:"Orange"},
{ css:"SS", title:"Banana"}
];
jQuery.grep(fruits,function(fruit){return fruit.title == 'Apple'});
I'm positive this question must have been covered before, but I can quite find it. So....
I have an object like so
Object
name: Fred
lastname: Jones
city: Los Angeles
I'd like to use Javascript to convert it to a string that looks like this:
//Do want this
[
{"name": "name", "value": "Fred"},
{"name": "lastname", "value": "Jones"},
{"name": "city", "value": "Los Angeles"}
]
All of the examples I've found use JSON.parse() to get a result that looks like this (which I don't want):
//Don't want this
[
{"name": "Fred", "lastname": "Jones", "city": "Los Angeles"}
]
I'm working with another developer who says this is how Jquery parses objects (EDIT- he's using $serializeArray(), so perhaps JQuery has a method to help me with this.
Any ideas would be most welcome.
Thanks!
This conversion calls for iterating through the properties of the source object and accumulating entries in a result array.
function toList( obj ) {
var rv = [], k;
for (k in obj) {
if (obj.hasOwnProperty(k))
rv.push({ name: k, value: obj[k] });
}
return rv;
}
var list = toList( myObject );
var arr = []
for (var key in object_name) {
arr.push({'name': key, 'value': object_name[key]})
}
Loop through the keys and add it to the array.
You can loop through the object properties and create the array
var a = array();
for (p in obj) {
a.push({'name': p, 'value': obj[p]});
}
This should get the structure that you want.
You should be able to do it in a simple for..in loop.
var yourObject = { name: "Fred", lastname: "Jones", city: "Los Angeles" },
parsed = [];
for(var i in yourObject){
parsed.push({ name: i, value: yourObject[i]})
}