Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to removeItem on localstorage but ı dont use localstorage.removeItem().Because ı want to delete a index in array(Sepet=array)
How can ı do it ?
thx
var array = [
{
'id': 1,
'name':'test1'
},
{
'id': 2,
'name':'test2'
},
{
'id': 3,
'name':'test3'
}
];
console.log(array);
localStorage.setItem('test', JSON.stringify(array));
var selected = 1;
var getArray = JSON.parse(localStorage.getItem('test'))
getArray.splice(selected,1);
localStorage.setItem('test', JSON.stringify(getArray));
console.log(getArray);
To get object from localStorage you need the Helper: localStorage.getItem('objectName');. You will get a string and not a object. To transform this string to a Object you need the function JSON.parse(string). And on this point you can work with the object. If you will delete item by index then remove it with object[index]and if you will remove item by value key like id: 2 then use JS Object function function like spliceto remove this item.
After that you have to stringify the object again to a string with JSON.stringify(object). This string you can store in the lcoalStorage withe the methode: localStorage.set(string)
That is the entire workflow.
localStorage is meant to store String values, so if you want to remove an item at a particular index, bear in mind that you need to convert the stringyfied array into plain JS array, then remove the item with array.slice(), and save the updated array back to localStorage.
You can checkh the Array.slice() documentation
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a function that returns the following:
{ 'random_string': '' }
Where random_string is an id that I do not know until it is returned.
How do I extract the value of random_string in JS? Thank you.
var a = { 'random_string': '' }
console.log(Object.keys(a)[0])
Your variable a has a value of type Object. Take a look at the Object prototype's documentation and see which methods are available to you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
You're trying to get your object's first key, and so conveniently you can use Object.keys as follows:
var a = { 'random_string': '' }
// Get array of Object's key values as strings
var aKeys = Object.keys(a);
console.log(aKeys);
// Print first key, in this case you only have one
console.log(aKeys[0]);
But based on your comments, you're going about this wrong.
If your "random_string" property identifier is truly random, you'd want to store the random string as an object property value.
That might look something like this:
// Generate some random string value
var random = Math.random().toString(36).substring(7);
// Create an object with a predefined object property identifier
var data = { 'random_value': random };
// Access the random value using your known property identifier
console.log(data.random_value);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The below code is a javascript interview question. I should get the output as [5,1,2,3,4]. Anyone can help me out this.
const input = [1,2,3,4,5]
const n = 4;
var output = []
console.log(output)
Without modifying the input array:
const input = [1,2,3,4,5]
const n = 4;
var output = []
output= [input[n],input.slice(0,n)].flat()
console.log(output)
From my understanding, the question is that when 'n' is a given index, you should be able to remove the element from the index n of the array and insert it at the very beginning of the array. As arrays are 0 based, it means that if n=4, then the element at nth index is 5 as per the given array.
In order to do that, you can do the following:
Use the splice method on the nth index and pass 1 as 2nd parameter, so you only remove the element at nth index.
Then use the unshift method on input to remove add the nth element at the beginning of the array. Unshift returns the length of the array, but you want the entire array to be stored in output.
So, you store the input array in the output variable.
Please run the below snippet for a better understanding. Let me know if my understanding of your question is not correct, so I can update my answer accordingly.
const input = [1,2,3,4,5]
const n = 4;
const [el] = input.splice(n,1); //array destructuring
input.unshift(el);
const output = input;
console.log(output)
const input = [1,2,3,4,5]
const n = 4
input.splice(0, 0, input[n])
input.splice(n+1, 1)
var output = [...input]
console.log(output)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
As the title suggests, how do I make a new object containing the 7 first keys of another object using JS? :) This is the structure of the object I would like to copy the data from.
{"data":[{"id":2338785,"team1":{"id":10531,"name":"Just For Fun"},"team2":{"id":10017,"name":"Rugratz"},"result":"2 - 0","event":{"name":"Mythic Cup 5","id":5148},"format":"bo3","stars":0,"date":1578279271000},....],"last_update":1578329378792}
Let's say there are 100 keys like this one, and I only want to copy the 7 first ones into a new object in JS.
Well technically, you have only 2 keys in the given Object but if you mean the data object, here's what you can do.
const MyNewObject = Object.entries(YourObject)
const results = []
and a simple for loop
MyNewObject.forEach((pair,i) => {
// for the 8th item it breaks and doesn't push it to results array
if ( i === 7 ) break;
results.push(pair)
}
OR u use slice instead :
// a little bit neater , and u call remove the empty results array above
const thisNewResult = MyNewObject.slice(0,6)
and finally the results is an array of key value pairs and you should do this code to make a new object from the results entries
const finalResults = Object.fromEntries(results)
Please notice that this may not be the Order you want since Object.Entries gives you the same order as the order of for in loop (for more info visit Elements order in a "for (… in …)" loop)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Currently I am having a problem with JavaScript arrays where if I update a value in an array it updates the value in both arrays.
My current array looks like this
billarr[camp][e].dataa = t;
For example if you try update the array like
billarr[22][1].dataa = "blabla";
It updates the dataa value in both
billarr[22]
and
billarr[23]
to the dataa var being "blabla"
I have spent hours looking what is the possible solution and am desperate if anyone has any advice
array population code
message ={};
temparr4 =[];
message.typee= $("#type"+data[i].id).val();
message.events= $("#event"+data[i].id).val();
message.network=data[i].network;
message.network_des=data[i].network_des;
message.dataa=data[i].data;
temparr4[data[i].id]=message;
and then loop(sets default array content)
camparr.forEach(function(i,e) {
billarr[e] = temparr4;
});
without using objects still has same array update issue.
message =[];
temparr4 =[];
message[0]= $("#type"+data[i].id).val();
message[1]= $("#event"+data[i].id).val();
message[2]=data[i].network;
message[3]=data[i].network_des;
message[4]=data[i].data;
temparr4[data[i].id]=message;
and then loop(sets default array content)
camparr.forEach(function(i,e) {
billarr[e] = temparr4;
});
This still updates both arrays billarr[22] and billarr[23]
billarr[camp][e][4] = t;
I have updates with code using no objects and just arrays but the array does the same as object and updates both arrays at specific element
You're constructing your array incorrectly, and storing the same object in two places in the array, rather than storing two separate objects.
You haven't shown nearly enough of your code for us to help you with it, but here's an example:
// An array
var a = [];
// An object
var o = {data: "foo"};
// Putting that object in the array
a.push(o);
// Putting it in again -- this results in the *same* object being in the array twice
a.push(o);
// If we change object...
a[0].data = "bar";
// ...it's the *object* that gets changed, so it doesn't matter which
// reference we use when looking at it:
console.log(a[0].data); // "bar"
console.log(a[1].data); // "bar"
console.log(o.data); // "bar"
The solution is to create a new object after pushing the old one onto the array
// An array
var a = [];
// An object
var o = {data: "foo"};
// Putting that object in the array
a.push(o);
// Creating a *new* object
o = {data: "testing"};
// Pushing the new object in the array
a.push(o);
// If we change object...
a[0].data = "bar";
// ...the other object isn't changed:
console.log(a[0].data); // "bar"
console.log(a[1].data); // "testing"