Convert String containing list of JSON objects to Object Array - javascript
A String contains list of Objects which are serialized in JSON format, how to convert that to list of JSON Objects like given in example below preferably without using jQuery.
Eval, Stringyfy Json.parse etc dont seems to help here.
[
{firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever#gmail.com'},
{firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou#gmail.com'},
{firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef#gmail.com'}
];
Update:- JSON String
[
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6yAAA"},"Name":"Stella Pavlova","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6yAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6zAAA"},"Name":"Lauren Boyle","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6zAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt70AAA"},"Name":"Babara Levy","Phone":"(503) 421-7800","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt70AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt71AAA"},"Name":"Josh Davis","Phone":"(503) 421-7800","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt71AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt72AAA"},"Name":"Jane Grey","Phone":"(520) 773-9050","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt72AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt73AAA"},"Name":"Arthur Song","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt73AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt74AAA"},"Name":"Ashley James","Phone":"+44 191 4956203","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt74AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt75AAA"},"Name":"Tom Ripley","Phone":"(650) 450-8810","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt75AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt76AAA"},"Name":"Liz D'Cruz","Phone":"(650) 450-8810","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt76AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt77AAA"},"Name":"Edna Frank","Phone":"(650) 867-3450","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt77AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt78AAA"},"Name":"Avi Green","Phone":"(212) 842-5500","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt78AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt79AAA"},"Name":"Siddartha Nedaerk","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt79AAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt7AAAQ"},"Name":"Jake Llorrac","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt7AAAQ"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6rAAA"},"Name":"Rose Gonzalez","Phone":"(512) 757-6000","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6rAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6sAAA"},"Name":"Sean Forbes","Phone":"(512) 757-6000","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6sAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6tAAA"},"Name":"Jack Rogers","Phone":"(336) 222-7000","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6tAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6uAAA"},"Name":"Pat Stumuller","Phone":"(014) 427-4427","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6uAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6vAAA"},"Name":"Andy Young","Phone":"(785) 241-6200","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6vAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6wAAA"},"Name":"Tim Barr","Phone":"(312) 596-1000","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6wAAA"},
{"attributes":{"type":"Contact","url":"/services/data/v30.0/sobjects/Contact/0039000000wvt6xAAA"},"Name":"John Bond","Phone":"(312) 596-1000","CreatedDate":"2014-05-15T06:17:48.000+0000","Id":"0039000000wvt6xAAA"}
]
I edited your post to make it more visibly clear, so maybe now you'll see: The value you posted as your "JSON String" is actually a JavaScript array of objects; exactly what you're claiming you're trying to convert the string into. You should read up more on JSON so you fully understand how you can convert to and from JSON, but that's already a valid JavaScript object -- you don't need to do anything to it.
Here's a JSFiddle showing this fact in action -- all you need to do is set a variable equal to the block of code you're receiving, and you can access it as a normal array/object. http://jsfiddle.net/ZpXVh/
var array = /* your really long code */;
alert(array[1]['name'];
Related
Problem with Child value from Vue component changing Parent value
I have an Array that I use to populate a Dialog Vue Component. I have: basicInfo: [{ firstName: "John" , lastName: "Doe" }], <basicInfoForm v-model="showBasicInfoForm" :basicInfo="newbasicInfo[0]"></basicInfoForm> on the Parent I have {{basicInfo[0].firstName + ' ' + basicInfo[0].lastName}} I have a button that will call a Form Component and open a Dialog popup that allows editing. My problem is that all changes to the Dialog are also immediately shown on the Parent. I would like to have on the Child Dialog a cancel button so no changes will be made. I cloned the array before I pass it: this.newbasicInfo = this.basicInfo.slice(); and on the Child Dialog <v-text-field v-model="basicInfo.firstName" label="First Name" class="input-name styled-input" ></v-text-field> props: { value: Boolean, basicInfo: Array }, My problem is that I can see each key stroke as changes are being made so there is no way to go back to the original if a cancel is selected. I'm new to Vue and Components so I could have something totally screwed up. Why are changes being make to both the basicInfo array and the newbasicInfo array at the same time.
What is happening here is that you are copying the array by reference. So when you modify the index of one array, actually both are modified because they share the same reference. What you need to do is to copy the array by values. this can be easily done this way : this.newbasicInfo = JSON.parse(JSON.stringify(this.basicInfo)); You can check this question on SO for more context : How do you clone an Array of Objects in Javascript?
Your clone method does not work with an array of objects: const basicInfo = [{ firstName: "John" , lastName: "Doe" }] const newbasicInfo = basicInfo.slice() This method creates a "shallow copy" - that means it works with numbers, strings, etc. but does not really create a clone of objects. The cloned objects this way keep their reference, so they will actually be the "same" objects as in the source array. const basicInfo = [{ firstName: "John" , lastName: "Doe" }] const newbasicInfo = JSON.parse(JSON.stringify(basicInfo)) This method creates a "deep copy" - everything it holds will be cloned, no matter how "deep" they are nested. If you have an array of simple values, the shallow copy is more efficient, but if you have objects in your array you need deep copy. So, it's not a Vue problem, but a more general JavaScript question. Here's a little snippet, to illustrate the difference: const basicInfo1 = [{ firstName: "John", lastName: "Doe" }] const newbasicInfo1 = basicInfo1.slice() newbasicInfo1[0].firstName = "Johnnyboy" console.log('basicInfo1: ', basicInfo1) console.log('newbasicInfo1: ', newbasicInfo1) const basicInfo2 = [{ firstName: "John", lastName: "Doe" }] const newbasicInfo2 = JSON.parse(JSON.stringify(basicInfo2)) newbasicInfo2[0].firstName = "Johnnyboy" console.log('basicInfo2: ', basicInfo2) console.log('newbasicInfo2: ', newbasicInfo2)
Printing Object doesnt contain all keys
Im completely lost. This is some test code I use to print a specific key of an object, then im printing the entire object. console.log(docs[0].mc_ign); console.log(docs[0]); Now this is the output I see on the console: The__TxT { id: 0, status: 1, testing: false, _id: 5dbc17eb20b3a8594d569570, timestamp: 2019-11-01T11:32:59.380Z, mc_uuid: 'dac89e44d1024f3b810478ed62d209a1', discord_id: '653029505457586176', email_address: 'gut97930#eveav.com', country: 'Germany', birth_month: 3, birth_year: 1943, about_me: 'about me text', motivation: 'motivation text', build_images: '', publish_about_me: true, publish_age: false, publish_country: true, __v: 0 } Where is the mc_ign key? The object itself comes from mongoose, the missing key is added by me after the fact: docs[i].mc_ign = mc_ign; I tried logging the entire object before and after I add the key and assign the value. They are both the same. What am I missing? Why can I read the value out, but cant see it?
It is mongoose document object. To achieve what you want do the following. docs[0] = docs[0].toObject(); docs[0].mc_ign = "stuff"; console.log(docs[0]) .toObject() convert it to plain JS object.
mapping through an array
I have an array called enquiries Im trying to map through it like this: enquiries.map(enquiry => enquiry.firstName) I get the following error: TypeError: enquiries.map is not a function Here is output for console.log(enquiries) {enquiries: Array(2)} enquiries:Array(2) 0:{_id: "5a28364d5a36f4556af34741", firstName: "jonny", surname: "rotten", telephoneNumber: 859937, gender: ""male"", …} 1:{id: "5a283e4c5a36f4556af34742", firstName: "bob", surname: "hoskins", telephoneNumber: 939483948, gender: "male", …}
The first {enquiries: Array(2)} implies that the logged element is an object that contains a key named enquiries. So if your logged variable is also enquiries then you need let firstNames = enquiries.enquiries.map(enquiry=>enquiry.firstName); Also to return the firstName from your arrow function, you need to either use {} and return inside it, or skip the {} altogether for an implicit return.
Well, you have two reasons for that. First, your "enquiries" variable is an object (but as it seems it's iteratable, that's good!). As an object, it doesn't have the map function in its prototype. Second, your arrow function uses curly brackets - which indicates that code should be written in. To use the shortcut for a single value you could either rid of the curly brackets or use regular ones: enquiries.map((enquiry) => (enquiry.firstName)) or even: enquiries.map(enquiry => enquiry.firstName) So for conclusion: Array.from(enquiries).map(enquiry => enquiry.firstName)
Hashes being pushed onto mongoose model as '[object Object]"
I am trying to push some things onto a Mongoose model. The model looks like this. var ScheduleSchema = new mongoose.Schema({ hours: Number, items: [{number: Number, minutes: Number, details: {description: String}, type: String}], userId: Number }); //later ScheduleSchema.methods.createNew = function(hours, tasks, breathers) { var schedule = makeSchedule(hours, tasks, breathers); console.log(schedule); this.items = schedule; console.log(this.items); } I think that is enough code for my issue, but I can give more code if needed. Essentially, I've got a method for creating a schedule and then I want to assign the schedule to the object's 'items' property. I must admit I am still learning about mongoose so it is likely a problem there. Anyway, I know my makeSchedule function is working, because I see this as the output from the first console message. [{ number: 1, minutes: 30, details: {description: 'Task A'}, type: 'task'}, { number: 2, minutes: 45, details: {description: 'Task B'}, type: 'task'}, etc... ] However, when the console output from my second log statement, this.items, prints, I don't see the same structure. Instead, I see ["[object Object]", "[object Object]", "[object Object]", etc...] Why am I not able to just assign the schedule variable to this.items? I believe I was even able to do it before, but I made some changes to my schedule code and now I cannot. That would lead me to believe that the error is in my schedule code, but as you can see, it is creating the list of items just fine, based on the console output. Can anyone see a really obvious, potentially mongoose related mistake that I may have missed as a rookie?
My guess is that you recently added the type field to the embedded objects in items which is making Mongoose now think that items contains an array of strings instead of an array of objects like you have. To fix it, use an object to define the type for type in your schema like so: var ScheduleSchema = new mongoose.Schema({ hours: Number, items: [{ number: Number, minutes: Number, details: {description: String}, type: {type: String} }], userId: Number });
Can't Delete Behaviour
I am having trouble with something that should be patently obvious. I cant seem to be able to delete properties of my object in node. This is in coffeescript, but I don't think that is relevant. console.log doc delete doc.password console.log doc Returns: { firstname: 'Andrew', lastname: 'Plummer', email: 'andrew#stackoverflow...', password: 'blahblah', _id: 5014c0a6af36bdaf03000001, comments: [], posts: [] } { firstname: 'Andrew', lastname: 'Plummer', email: 'andrew#stackoverflow...', password: 'blahblah', _id: 5014c0a6af36bdaf03000001, comments: [], posts: [] } For something so seemingly obvious I have actually searched around stackoverflow and googled for about half an hour. Sorry if still i have missed a duplicate.
The answer as given by Frédéric in the comment ( so i cant mark it as true) is that my object needed to be explicitly turned into a new object as it had its delete disabled. This is the case with mongoose ODM models in node.