Pushing data to an array inside another array with Javascript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I made an array for a raffle system using node.js and discord.js which has this data set.
[{"author":"Name","rafflename":"RAFFLE","amount":"10","entries":"[]"}]
When someone tries to enter the raffle I'd like to make another JSON array inside the entries tag.
The problem i face is when i use raffles[0].entries.push({ 'username': 'example', 'user_id': '1' });
It returns an error: raffles[0].entries.push is not a function
I assume this is because it is looking for the array raffles[0].entries.push which does not exist. But I've only ever used the push command. So I am not sure how to fix this issue.

Move your entries [] out of double quotes, i.e. Use "entries" :[]
You are trying to push to a string instead of array

You have to cast entries to Array first.
const raffles = [{"author":"Name","rafflename":"RAFFLE","amount":"10","entries":"[]"}]
// cast entries to Array
raffles[0].entries = JSON.parse(raffles[0].entries)
// now you can push them
raffles[0].entries.push('test')
console.log(raffles)

It isn't working because you have "" around the properties inside of your object. you can fix this by either removing the "" or doing this:
raffles[0]['entries'].push(//your code here);
When properties of an object are strings (i.e. when they have quotes around them) you must access that property using "dot notation"
eg:
var object = {"property":"five"};
console.log(object["property"]); //prints 'five'
console.log(object.property); //throws an error

Format Your Array according to #Bibberty Comment and do operation
raffles=rafale=[{"author":"Name","rafflename":"RAFFLE","amount":10,"entries":[]}]
raffles[0].entries.push({ 'username': 'example', 'user_id': 1 });
console.log(raffles)

Related

Why am i getting 'undefined' from this JSON object? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
var action=component.get("c.callCostCatalog");
action.setParams({ wrapperStructure:JSON.stringify(component.get("v.listStructurePV")),
consumoTotal:component.get("v.consumTotal"),
Rate:'Vacia',
orderItemID: component.get("v.recordId"),
PMPInicial:component.get("v.precioInicial")})
action.setCallback(this,function(response){
//var listWrapper = JSON.parse(response.getReturnValue()); -> log shows [object object]
var listWrapper = JSON.parse(JSON.stringify(response.getReturnValue()));
//listWrapper.usedBand returns undefined
})
callCostCatalog is an Apex method which returns the string:
{"usedBand":0.0,"PMPObjetivo":0.0,"PMPNegotiated":0.028533,"PMPInit":0.028533,"negotiationBands":null,"Negotiation":0.0,"negBandCI":null,"minBandSD":null,"minBandRZ":null,"minBandRT":null,"minBandD":null,"minBand":null,"maxBandSD":null,"maxBandRZ":null,"maxBandRT":null,"maxBandD":null,"maxBand":null,"lNegotiatedPrices":[80.97],"lInitPrices":[0.028533],"lImplicitPrice":[],"lConsums":[]}
var aux = '{"usedBand":0.0,"PMPObjetivo":0.0,"PMPNegotiated":0.028533,"PMPInit":0.028533,"negotiationBands":null,"Negotiation":0.0,"negBandCI":null,"minBandSD":null,"minBandRZ":null,"minBandRT":null,"minBandD":null,"minBand":null,"maxBandSD":null,"maxBandRZ":null,"maxBandRT":null,"maxBandD":null,"maxBand":null,"lNegotiatedPrices":[80.97],"lInitPrices":[0.028533],"lImplicitPrice":[],"lConsums":[]}';
It starts out as a string of JSON that represents an object.
JSON.stringify(aux)
Then you turn it into a string of JSON (that represents a string of JSON that represents an object).
JSON.parse(...);
Then you parse it, which gives you the original string of JSON back.
Strings don't have usedBand properties.
You need to parse your original JSON without converting it to nested JSON first.
var aux = '{"usedBand":0.0,"PMPObjetivo":0.0,"PMPNegotiated":0.028533,"PMPInit":0.028533,"negotiationBands":null,"Negotiation":0.0,"negBandCI":null,"minBandSD":null,"minBandRZ":null,"minBandRT":null,"minBandD":null,"minBand":null,"maxBandSD":null,"maxBandRZ":null,"maxBandRT":null,"maxBandD":null,"maxBand":null,"lNegotiatedPrices":[80.97],"lInitPrices":[0.028533],"lImplicitPrice":[],"lConsums":[]}';
var aux2 = JSON.parse(aux);
console.log(aux2.usedBand);
Your JSON.parse is right, and your console.log is right, and your JSON is valid.
However, you have erroneously called JSON.stringify, which is like the reverse of parse, taking a JavaScript object and producing a string of JSON. You don't want that; you already have a string of JSON. Simply remove it.

Array[key].push Is Not Defined in JavaScript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
When trying to push items to an array in javascripts it gives an error, the following pseudo code illustrate what is happening:
var data = new Array();
for(...) {
data[key].push(item[i]);
}
It is showing the following error:
Cannot read property 'push' of undefined
Thanks
If you need a 2d array, you have to initialize each element of the outer array to be an array.
// Have to check every array item, if it's not an array already, make it so
for(...) {
if (!data[key]) {
data[key] = [];
}
data[key].push(item[i]);
}
You could always do the following if you know the number of inner arrays you need:
var data = [[],[],[],[],[],[]];
In your example, since they variable name is key, I'm assuming you actually want an object of arrays. If you know the keys ahead of time, you can use the following literal.
var data = {
myKey1: [],
myKey2: []
}

How can I get the contents of an array out of an object? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a variable which looks like this when I log it:
console.log(msg)
["The Email must be at least 10 characters long."]
I thought this meant that the text is inside an array as the 1st and only element. However
when I try to get the first element it gives me:
console.log(msg.[0]))
SyntaxError: Unexpected token [
How can I extract the text from the msg variable?
To get the contents of an array:
for (var i = 0; i < yourArray.length; i++) {
console.log(yourArray[i]);
}
To get the contents of an object:
for (var obj in myObject) {
console.log(obj);
}
You're syntax is wrong, instead you need:
console.log(msg[0]))
[] accessors are used for array access, or to access an object property via a string myObj["value"]
. accessors are used for fields when you know the name so you could use myObj.value
simply remove the . when accessing individual array elements.
therefore it becomes :
console.log(msg[0]);
Take the dot in msg.[0] out.
console.log(msg[0])
should retrieve your text correctly.

Defining String Arrarys [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Hi I'm a beginner in Javascript and somethinh strange occured.
I wanted to create an global String array in an external Javascript file with
var natArray = new Array(20); But my IDE(Webstorm 7) Says me newArray is an Unresolved function and I cant use the array in another function it was created for(Source: Javascript Console)
Thank you for your time and feedback.
EDIT: Rest of the Code
function country(name){
for(i=0;i<20;i++)
natArray[i]=name;
document.write(natArray[i]);
}
And here i call it(a html file):
Country:
<select>
<script type="text/javascript">
country("RandomCountry1");
country("RandomCountry2");
</script>
</select>
Im just getting an empty drop-down-list
I'm not sure what you are trying to accomplish, but the reason that document.write(natArray[i]); is returning undefined is that you are leaking i to the global scope in for(i=0;i<20;i++).
Once this loop has completed, i is equal to 20, even outside the scope of the loop (to avoid this, try for(var i=0;i<20;i++). Although natArray has a .length of 20, arrays elements are zero-indexed, meaning that they start counting at 0, not 1.
Because of this, if what you are trying to do is access the last element of natArray, you can/should do so with natArray[natArray.length - 1]. The -1 accounts for the zero-indexed nature of Javascript arrays. If natArray has a length of 20, you will fail to access natArray[20] because this statement is actually trying to access the 21st element, not the 20th.

JSON parsing not working in jQuery [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have a text field with id search_json on a form that contains:
{"standard_id":"2","attribute1":["","Stan"],"attribute2":[""],"attribute3":["","Air Force"],"attribute4":["","Bob"],"selected_index":3}
Upon some event, call it a button click, I want to:
1) Read in that JSON and parse it into an object:
search_json = $.parseJSON($("#search_json").val())
2) Remove "attribute1" from the object
delete search_json["attribute1"]
3) Write the JSON back out to the text field:
$("#search_json").val(JSON.stringify(search_json))
I'm kind of surprised it's not working, though. The delete call does nothing. As a matter of fact,
search_json.hasOwnProperty("attribute1")
returns false. And yet I can log the object to console and it is indeed an object with those values. What is going wrong here?
UPDATE: Actually,
search_json.hasOwnProperty("attribute1")
DOES work. But, if I get the attribute name from another text field, like so:
attribute_name = $("#attribute_name").attr("id")
and:
console.log attribute_name
shows "attribute1", then this does NOT work:
search_json.hasOwnProperty(attribute_name)
returns FALSE. Mystifying.
I don't get it. I'm using your fiddle code and everything is correct
http://jsfiddle.net/ddQbe/1/
The final object is:
attribute2: Array[1]
attribute3: Array[2]
attribute4: Array[2]
selected_index: 3
standard_id: "2"
attribute1 was delete correclty
I would try creating a new result_json object.
var result_json = {};
for (var prop in search_json) {
if (prop !== 'attribute1') {
result_json[prop] = search_json[prop];
}
}
$("#search_json").val(JSON.stringify(result_json));

Categories

Resources