jQuery substring - javascript

I have a key value pair something like this. this response comes back from the service in API.
var str = { "key1":"value1",..}
I need to use something lik this
for(var value in str) {
//I need to get only the value here. Eg: value1,value2 etc
}
how to get only value1 from this array using jquery sub string?

You can loop through an object (= key/value store) like this:
for (var key in items) {
var value = items[key];
// do things with key and value
}

If the response comes back as a set of (key, value) pairs, then you cannot really select the "first" value, because JSON objects do not have an order to their fields (different parsers may and probably will return the values in different order). You must know which key you want to access.

var str = { "key1":"value1",..}
for(var val in str) {
var strval = str[val];
}

var str = { "key1":"value1","key2":"value2","key2":"value2"};
var keyItems,valItems;
for(key in str){
keyItems.push(key);
valItems.push(str[key]);
}
// keyItems is array of all keys
// valItems is array of all values.

Related

Converting JSON value into JavaScript array

I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);

How to remove double quotes from json array in javascript

I have a array :
Var array=[{"name":"May","data1":"1121.0"}]
I want to change it to :
Var array= [{"name":"May","data1":1121.0}]
You can simply check using Number.isNaN with an attempted cast to a number using the + operator. If it returns true then do nothing. If it's false then change the value of the parameter to a cast number.
var array=[{"name":"May","data1":"1121.0"}];
array.forEach(data => {
for(let key in data) Number.isNaN(+data[key]) || (data[key] = +data[key])
});
console.log(array);
Looks like this has been answered before here
I'll summarize;
for(var i = 0; i < objects.length; i++){
var obj = objects[i];
for(var prop in obj){
if(obj.hasOwnProperty(prop) && obj[prop] !== null && !isNaN(obj[prop])){
obj[prop] = +obj[prop];
}
}
}
console.log(JSON.stringify(objects, null, 2));
This does have a bug where 0 becomes null.
You want to convert the value mapped to the "data1" key to be a number instead of a string.
There are many ways to accomplish this in JavaScript, but the best way to do so would be to use Number.parseFloat like so:
var array = [{"name":"May","data1":"1121.0"}];
array[0]["data1"] = Number.parseFloat(array[0]["data1"]);
console.log(array[0]["data1"]); // 1121
If you need to perform this action with multiple objects inside of array, you could do
var array = [{"name":"May","data1":"1121.0"}, {"name":"May","data1":"1532.0"}, etc.] // Note that this is not valid JavaScript
array.map(obj => {obj["data1"] = Number.parseFloat(obj["data1"]); return obj;});
If I understood well, you only want to convert the value of data1, from "1121.0" to 1121.0, in other words from string to number.
To convert only that key (data1), you only need this:
array[0].data1 = parseFloat(array[0].data1)
If that's not what you want, please explain better your question

How to add Key on existing array javascript

im currently working on a project that uses javascript as it's front end and im having a bit trouble on adding a key on my existing array.
i have an object that i wanted to be converted on array javascript.
here is my code on how to convert my object to array.
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) { return obj[key]; });
var site_key = $.map( obj, function( value, key ) {
return key;
});
the site_value has the value of my objects.
the site_key has the key.
i want to add my site_key to the site_value array as a Key.
example data:
site_value:
0:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
site_key:
Array[49]
0:"AGB"
1:"BAK"
2:"BAN"
3:"BAR"
i want my array to be
AGB:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
Update:
Here is my object.
Array[1]0:
Object
AGB: Array[4]
BAK: Array[4]
BAN: Array[4]
etc.
You have almost done it and I have modified it a bit below to return it as array object,
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) {
var output = {};
output[key] = obj[key];
return output;
});
I might be misunderstanding the question, sorry if I am. I think you would like to use a key "AGB" instead of an integer for an array index. In this case, you would probably be better served to use an object instead of an array. Maybe something like this
var myObject = {
AGB: Array[4],
AGBarrays: [Array[4],Array[1],Array[1],Array[0]]
};
Then you could access AGB by key and your additional arrays by index

Jquery fill object like array

This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).

How do I change a JSON object into an array key/value pairs through code?

How do I change a JSON object into an array key/value pairs through code?
from:
{
'name':'JC',
'age':22
}
to:
['name':JC,'age':22] //actually, see UPDATE
UPDATE:
...I meant:
[{"name":"JC"},{"age":22}]
May be you only want understand how to iterate it:
var obj = { 'name':'JC', 'age':22 };
for (var key in obj)
{
alert(key + ' ' + obj[key]);
}
Update:
So you create an array as commented:
var obj = { 'name':'JC', 'age':22 };
var obj2 = [];
for (var key in obj)
{
var element = {};
element[key] = obj[key]; // Add name-key pair to object
obj2.push(element); // Store element in the new list
}
If you're trying to convert a JSON string into an object, you can use the built in JSON parser (although not in old browsers like IE7):
JSON.parse("{\"name\":\"JC\", \"age\":22}");
Note that you have to use double quotes for your JSON to be valid.
There is no associative array in JavaScript. Object literals are used instead. Your JSON object is such literal already.

Categories