Converting array in object to string - javascript

I want the array in an object to be a string. can someone pl help? So im passing an array into an object and Im expecting var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort'; how can this be attained ?
it("should serialize an object with another object/array in it", function() {
var object2 = {
'name': 'bob',
'age': 24,
'kids': [ 'billy', 'bart', 'bort' ]
};
var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort';
expect(NUUI.Utils.serializeForQueryString(object2))
.toEqual(expectedResultForObject2);
});

You need serialized result from an object. This can be achieved with jQuery.param()
uri = $.param(object2);
More information on this, you can find in jQuery Manual.
Alternatively, you can make an array object a string simply with .join() method of the array
string = array.join('');
This question is heavily answered in SO
jQuery serialize an object?

Related

How can I add the data of one JS object to another

In the function there is an empty JS object
var globalDataObject = [{}];
Then, there is a loop that goes over an array of users, stores the properties of each user in variables (ex. name, lastName, ...) and creates an object for each user:
//create an object containing the current name
const currentObject = {
'profile': {
'name': nameVariable,
'lastName': lastNameVariable
}
};
What is the right way to add the data of currentObject to the globalDataObject once it's created? So that at the end the globalDataObject should be:
var globalDataObject = [
'profile': {
'name': 'John',
'lastName': 'Smith'
},
'profile': {
'name': 'Ann',
'lastName': 'Lee'
},
'profile': {
'name': 'Dan',
'lastName': 'Brown'
}
];
Important thing is that globalDataObject must be the JS object of the specified format (not the object containing multiple objects and not the array) since once it's created it is going to be converted into XML.
You can create your global object like an array:
globalDataObject = [];
And then just push in it:
globalDataObject.push(currentObject);
I dont understand the end goal of the question and why you dont just use .push() as suggested before. You havent accepted that answer so i assume its not the end goal.
globalDataObject must be the JS object of the specified format (not
the object containing multiple object and not the array)
1) The format you gave is not valid JavaScript.
2) Why cant you have an array of objects or object with nexted objects and covert that into xml
3) Why do you want to convert json into xml in the first place.
I'll take a wild guess and assume you mis-typed the globalDataObject as array, and meant it to be an object with multiple 'profile' keys. Neither is valid javascript.
Since you can't have multiple keys with same name and expect them to have different values, I propose you to use unique "indexes" for each profile.( like an array...but an object).
// init the object
const userProfiles = {};
// then later add to it like this.
let profile1 = {name: "john", lastname: "smith"};
let profile2 = {name: "alice", lastname: "wonderland"};
userProfiles[1] = profile1;
userProfiles[2] = profile2;
// you can then torn it into an array of user profile objects like this
Object.keys(userProfiles).map((index) => {return userProfiles[index];})

How to convert data to string

I have data for example like this:
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}]
And I want to convert them into like this:
data: ['Apple','Microsoft','Google']
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
One way is to use Array.map and replace the object ele.tag with just the value return ele.tag:
var data =
[{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}];
data = data.map(function(ele){ return ele.tag; });
console.log(data);
Or in ES6 you can simply this even more:
data = data.map(ele => ele.tag);
You could use a for-in loop and push the attribute of the object into an array.
var data = [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}];
var tags = [];
for (prop in data) {
tags.push(data[prop].tag);
}
console.log(tags);
For easier handling let's take the object in the OP's code and assign it to a variable, as follows:
var obj = {"data":[{"tag":'Apple'},{"tag":'Microsoft'},{"tag":'Google'}]};
var {data}= obj; // object destructing ...
var mapped = data.map(function( e ){ return e.tag});
// re-assigning value of object's data property
obj["data"] = mapped;
console.log(obj); // obj.data now pertains to array of strings
The problem described by the OP involves an object whose data property refers to an array of objects, each with a tag property. The OP inquires as to how to revise the data property so that it refers instead to an array of string values corresponding to each object's tag property.
This example makes use of destructuring to access the array of objects. Then, it uses the array's map() method to access every element's tag property and thereby obtain its string value. The beauty of map() is that it performs iteration behind the scenes sparing the user from having to hand-code a loop with the correct logic -- although in functional programming languages instead of using iteration, recursion is more apt to be utilized for this purpose. Finally, the value of the object's data property is reset to contain the specified array of strings.

Output value from Json Array

I'm getting output: [{"ref":"contact.html","score":0.7071067811865475}]
$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});
How can I print value of ref? When I console.log(final[0].ref); I get undefined.
EDIT:
JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'
To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:
final = JSON.parse(final)
console.log(final[0].ref)
If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:
var arr = [
{"ref": "object1", "score": "1"},
{"ref": "object2", "score": "2"}
]
arr.map(function(object) {
console.log(object.ref)
})
JSFiddle using an alert instead of console.log()
You can also use a loop, but this cleaner.
var a = [{"ref":"contact.html","score":0.7071067811865475}];
a[0].ref;
a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.
Expanded out a bit:
var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
console.log(myObject.ref ? myObject.ref : 'no value');
}
Well, assuming
var myvar = [{"ref":"contact.html","score":0.7071067811865475}];
then:
var myref = myvar[0].ref;

Confuse about array and object in node.js

I have a array for store object, which have an object in it already:
var obj = [{
name: 'json',
lang: 'en'
}];
console,.log(obj) //the result is OK;
then I want push another object into it, just like:
var newObj = {
name: 'lee',
lang: 'zh'
}
obj.push(newObj)
but after this I print the obj array,console.log(obj), the result is 2 !!
Why this happen? How can I solve this problem?To store object in array correctly
Make sure you didn't do obj = obj.push(newObj);, because .push method returns the number of elements after push; instead, the line should simply read obj.push(newObj).

Converting javascript dictionary to array/object to be passed in jquery.params

I have a javascript variable which is a dictionary of key-values pairs of querystring. I need to again convert this dictionary into a query string. I am using jquery.param functin but it takes either an array or an object. How can I convert my dictinoary variable to array/object which jquery.params can accept.
Tried using serializeArray but it does not work.
The jQuery.param method can take an array i in this form:
[{ name: 'asdf', value: '42' },{ name: 'qwerty', value: '1337' }]
If your dictionary have other property names, you can use the jQuery.map method to convert it. Example:
arr = $.map(arr, function(e){
return { name: e.key, value: e.val };
});
If I understand your question right (some code samples would help!) by "dictionary" you mean a construction like:
var dict = { key1: value1, key2: value2 … }
or:
var dict = {};
dict[key1] = value1;
dict[key2] = value2;
or possibly:
var dict = {};
dict.key1 = value1;
dict.key2 = value2;
If so, you should know that all of these are doing the same thing, i.e. setting properties on JavaScript objects, and should be serialised correctly by jQuery.param. Succinctly, JavaScript objects ≈ dictionaries.
use Object.values() :
var arr = Object.values(some_dict)

Categories

Resources