When I write 'document.write() on an array result it gives me [object,Object] instead of array content.
document.write(result) was expecting the array content not [object,Object]
I am 77yrs old and learning JS, I know this Question may look naive but I have got stuck on this, trying to get the result on screen not console.log
The reason you are getting [object,Object] is because you are trying to render the entire object - instead of its properties. So - assuming you are trying to print out the results of an array - as indicated in the post ... a simple array of two people with first and last names in object notation. Also - note the use of the template literals - makes it very easy to interact with and render the js content.
Simply iterate over the array and print out the indicated properties....
Note that I would not suggest to use document.write() - nor the html 'br' element - but to keep it in line with what you have presented - I did...
I would create a single string and insert it into the DOM in a ul / li strucuture...
const results = [
{firstName: 'Bob', lastName: 'Smith'},
{firstName: 'Jane', lastName: 'Doe'}
]
results.forEach(result => document.write(`${result.firstName} ${result.lastName} <br/>`));
// gives
//Bob Smith
//Jane Doe
Related
I am obtaining the response from the server in JSON format. This JSON may constitute objects with duplicate Keys. When I was displaying the result the duplicate key values were getting committed. After debugging I found out that this is happening because of the JSON.stringify method that I am performing to format the code before providing to the front-end.
As of now when I perform the JSON.stringify then it removes the duplicate entries and provides only the last value for the duplicate keys however I would like to retain everything.
var obj = {name: "John", age: 30, name: "New York"};
var result = JSON.stringify(obj).replace(/\_/g, '');
console.log(result);
//{"name":"New York","age":30}
As we can see the first name has been committed. How to modify the code so we can retain all values of the duplicated key?
Please Note:
As of now, I have provided the sample code that has the duplicate key name. However, when I am getting the response from the server I am unaware of what key might be duplicated so I am looking for a general solution that can work for everything rather than hard-coded logic that works only for name.
Any suggestions or workarounds would be really appreciated.
Json objects don't allow duplicated keys.
If you execute just:
var obj = {name: "John", age: 30, name: "New York"};
console.log(obj)
You will see that you have already lost the first "name" value.
The only work around that I can think of, is to never transfor the received JSON String to an Object.
Or you can manually write a logic to split this json string by commas, and transform it into a JSON object according to you need, but without duplicated keys, for example:
{name: ["John", "New York"], age: 30};
Looking for clean way to convert a javascript object containing arrays as values to a search param compatible query string. Serializing an element from each array before moving to the next index.
Using libraries such as querystring or qs, converts the object just fine, but handles each array independently. Passing the resulting string to the server (which I cannot change) causes an error in handling of the items as each previous value is overwritten by the next. Using any kind of array notation in the query string is not supported. The only option I have not tried is a custom sort function, but seems like it would be worse than writing a custom function to parse the object. Any revision to the object that would generate the expected result is welcome as well.
var qs = require("qs")
var jsobj = {
origString:['abc','123'],
newString:['abcd','1234'],
action:'compare'
}
qs.stringify(jsobj,{encode:false})
qs.stringify(jsobj,{encode:false,indices:false})
qs.stringify(jsobj,{encode:false,indices:false,arrayFormat:'repeat'})
Result returned is
"origString=abc&origString=123&newString=abcd&newString=1234&action=compare"
Result desired would be
"origString=abc&newString=abcd&origString=123&newString=1234&action=compare"
I tried reorder your json:
> var jsobj = [{origString: 'abc', newString: 'abcd' }, {origString: '123',
newString: '1234' }, {action:'compare'}]
> qs.stringify(jsobj,{encode:false})
'0[origString]=abc&0[newString]=abcd&1[origString]=123&1[newString]=1234&2[action]=compare'
But I don't know if this is a good alternative for your problem.
Chalk this up to misunderstanding of the application. After spending some more time with the API I realized my mistake, and as posted above by others, order does no matter. Not sure why my first several attempts failed but the question is 'answered'
This question already has answers here:
Converting a string to JSON object
(10 answers)
Closed 4 years ago.
It might sound like a bit of a weird question, but i've always struggled to understand the different structures of arrays and objects when passing them via JSON.
How would I build an array in PHP, and pass it back via JSON so that when i console log it out, it displays as a list of array objects like this?
At the moment this is my code
$users = [];
foreach($users as $key => $user){
$array = [];
$array['username'] = $user->username;
$array['id'] = $user->id;
array_push($users, $array);
}
return response()->json(['list'=> $users]);
But this returns it so it looks like this
{list: [{username: 'Joe Bloggs', id: 1}, {username: 'John Smith', id 2}]}
in the console log.
How would i structure my php so that when I pass it back via JSON, and console log it out in the browser, it looks like the picture above? With a dropdown arrow, and an array of objects for me to click through?
The different types of arrays and objects always confuses me, and I kind of just do trial and error until it works the way I want, but I want to understand how it works.
I just cant seem to wrap my head around it!
EDIT
Just to add some extra information to try and get across what I am trying to do.
At the moment my javascript is console.log('Data Returned', result);.
In my PHP, if I grab a class in Laravel using
return response()->json(['list'=> User::all()]);
When I pass it back, it displays like the picture I have attached, with a dropdown and an array of objects.
If I then change the PHP to try and build the object myself before passing it back, and I change it to the above PHP code, it displays like this in the console log {list: [{username: 'Joe Bloggs', id: 1}, {username: 'John Smith', id 2}]} without me changing the javascript.
How do I manually build an object in PHP, so that when I pass it back, it console logs out like the picture above, with an array of objects and a dropdown to click through them all?
Yes, the above json returned by php is exactly what you want. Here, list is an array of objects. In your example you list array has two objects. You can access them through . or ['key'].
Suppose you assign your JSON response object to some variable json like below-
var json = response;
// now you can fetch name of first element by -
json.list[0].username;
// for the second username
json.list[1].username;
// you can iterate over the list like (forEach in javascript)
json.list.forEach(function(object,index){
// this will print the username of each object stored as element in list array
console.log(object.username);
// suppose you have used jquery and your select has id="userId" then following line of code simply add them in your select list
$('#userId').append('<option value="'+object.id+'">'+object.username+'</option>');
});
Remember array can be of any type - integer,array,objects,string. If array elements are like [1,2,3,4,5] then it's array of integer, if array elements are like ['some','words','goes','here','like','this'] then it's an array of strings. If array elements are like [[1,2,3],['some','words','here']] then it's array of array ... and your output above is array of objects.
feel free to ask question.
Lets say I have an data like:
{username: 'Joe Bloggs', id: 1} //JSON object notation
Standard PHP array:
$array = array(
'username' => 'Joe Bloggs',
'id' => '1'
)
If that was stored as an array in a variable called $array, then I would access it like this in PHP:
$array['username'] //Joe Bloggs
If it was stored as an object $object, then I would access it like this:
$object->username //Joe Bloggs
In js the arrays are the similiar:
array['username'] //Joe Bloggs
But objects are like this:
object.username //Joe Bloggs
If I want to save a value to a variable in PHP:
$array['username'] = 'Joe Bloggs';
$object->username = 'Joe Bloggs';
And in js it is like this:
array['username'] = 'Joe Bloggs';
object.username = 'Joe Bloggs';
Now you just need to know if your dealing with an array or object. Js deals with alot of objects. The thing with objects is that you are really accessing properties of that object. Properties can be functions as well. If an object has a method/function say getId(). Then you can:
In PHP:
$object->getId();
And in js:
object.getId();
I probably butchered this really bad, but that the very basics.
I have a handful of arrays one of first names, one of last names, and one of emails. I want to create an object for each index of the arrays.
firstnames[0], lastnames[0], emails[0]
would become
{firstname: value, lastname: value, email: value}
from which I would take that object and throw it in an array. However currently I am having trouble trying to figure out how to tackle this I can't wrap my brain around it. Hoping someone can help me come up with a clean method of doing this.
You just need a loop. On each iteration of the loop get the value from each array for the current index. A simple for loop would be easiest to understand.
The following uses the array .map() method to do this. That iterates over firstnames and builds a new array containing whatever values are returned by the function passed to .map() as an argument. The advantage of this is that you don't have to manually create an output array and push objects into it, .map() does that part for you, and also it avoids creating any working variables in the current scope.
This assumes all arrays are the same length.
var firstnames = ['Annie', 'Ben', 'Chris']
var lastnames = ['Andrews', 'Brown', 'Carmichael']
var emails = ['a#a.com', 'b#b.com', 'c#c.com']
var output = firstnames.map(function(v, i) {
return {
firstname: v,
lastname: lastnames[i],
email: emails[i]
}
})
console.log(output)
I'm calling an external service and I get the returned domain object like this:
var domainObject = responseObject.json();
This converts the response object into a js object. I can then easily access a property on this object like this
var users = domainObject.Users
Users is a collection of key/value pairs like this:
1: "Bob Smith"
2: "Jane Doe"
3: "Bill Jones"
But CDT shows users as Object type and users[0] returns undefined. So how can I get a handle to the first item in the collection? I'm assuming that some type of type cast is needed but not sure how I should go about doing this
UPDATE
Here is one way I could access the values:
//get first user key
Object.keys(responseObject.json().Users)[0]
//get first user value
Object.values(responseObject.json().Users)[0]
But I need to databind through ng2 so I was hoping for a simpler way like this:
<div>
<div *ngFor="let user of users">
User Name: {{user.value}}
<br>
</div>
</div>
Maybe I should just create a conversion function in my ng2 component which converts the object into what I need before setting the databinding variable?
UPDATED ANSWER
So after scouring through a few docs I found the "newish" Object.entries() javascript function. You can read about it here. Pretty cool.
Anyways, give this a try. I am ashamed to say that I don't have time to test it, but it should get you going in the right direction.
usersArray = []
// Turn Users object into array of [key, value] sub arrays.
userPairs = Object.entries(users);
// Add the users back into an array in the original order.
for (i=0; i < userPairs; i++) {
usersArray.push(_.find(userPairs, function(userPair) { return userPair[0] == i }))
}
ORIGINAL ANSWER
I would use either underscore.js or lodash to do this. Both are super helpful libraries in terms of dealing with data structures and keeping code to a minimum. I would personally use the _.values function in lodash. Read more about it here.. Then you could use users[0] to retrieve the first item.
The only caveat to this is that lodash doesn't guarantee the iteration sequence will be the same as it is when the object is passed in.
users = _.values(users);
console.log(users[0]);
How about this:
let user= this.users.find(() => true)
This should return the "first" one.
If your initial object is just a plain object, how do you know it is sorted. Property members are not sorted, ie: looping order is nor guaranteed. I´d extract the user names into an array and the sort that array by the second word. This should work (as long as surnames are the second word, and only single spaces are used as separators).
var l=[];
for(var x in users) {
push.l(users[x]);
}
var l1=l.sort ( (a,b) => return a.split(" ")[1]<b.split(" ")[1]);