Push array into JSON Object, Javascript - javascript

I am trying my best to program an angular app. I have a problem pushing an empty array into an object.
I get an error:
TypeError: Cannot read property 'push' of undefined
I have an object called items which looks like this:
Object
{
"Name": "name",
"Description": "description"
}
I would like to push an empty array into the object that can contain another array. Something like this.
Object
{
"Name": "name",
"Description": "description",
"Related Items": {
Item1:{...},
Item2:{...},
...
}
}
My controller does this when it is called:
$scope.push = function () {
$scope.item.push({"Related Items":[]});
};
I know I must be getting mixed up with something simple about the JSON Objects and Arrays, but I can't seem to find a solution.
Thankyou!

Since item is an object, you can just set the Related Items property:
$scope.item["Related Items"] = [];
$scope.item["Related Items"].push({});
However, above it looks like Related Items is actually an object with key names Item1, etc. rather than an array.
$scope.item["Related Items"] = {};
$scope.item["Related Items"].Item1 = {};

Javascript's push function only works when you're pushing values to an array. It won't work if you try to push to an object, instead it will try to call the key of "push" which doesn't exist. That's why you're getting the error you're getting.
Make sure that $scope.item is an array ([] or new Array), and then push to it with the value you would like.
$scope.item = [];
$scope.push = function () {
$scope.item.push({"Related Items":[]});
};
Here's W3School's .push() method explanation.

The item object should be like
{
....
"Related Items":<"some value">
....
}
It should already have key.

Related

How to get a JSON object's key from the object itself in JavaScript/a Vue v-for loop?

I'm not looking for the keys that this object contains but the key of the object itself (the key in the array containing the object).
I have this JSON:
{
"Object name (text)": {
"raw": "Some more text.",
},
"Another name": {
"raw": "Some other text.",
}
}
and would like to get "Object name (text)" for the first item.
My Vue code is:
<CustomComponent
v-for="object in objects"
:key="getKey(object)"
:object="object"
/>
I'm not sure if the getKey-method approach is how one is intended to get unique identifiers for iterating through the JSON array. Its code currently is:
getKey(object) {
return Object.keys(object)[0];
}
Now I'd like to somehow pass the name of the object to the CustomComponent ("Object name (text)" in the first case).
One temporary workaround that I intended to use until I find something more appropriate was getting the keys from the objects array like so:
:objectName="getObjectName(object)" and itemNumber: -1 in data and this method:
getObjectName(object) {
this.itemNumber = this.itemNumber + 1;
var objectName = Object.keys(this.objects)[this.itemNumber];
console.log("Object name: ", objectName);
}
However, the first line of this method causes it to run hundreds of times instead of only two times (why is that?; it works in the first 2 executions of the method and when commenting out that line) and I think this is unlikely the proper method to simply retrieve the object's name/key.
It also didn't work when putting the above code into the getKey method which would make more sense (and I had the code in that method before creating a separate method to debug). Then the key could be accessed in the component with this.$vnode.key However, it keeps being undefined. This might be a separate problem even though it could resolve this problem here as well - I might create a new question for it. It enters the methods "getKey" and "getObjectName" 6 times each even though it only renders two items on the page, like it should.
-> How to get the JSON object's key in JavaScript?
(Preferably from the object itself after iterating through a JSON array with a loop with Vue instead of only indirectly by checking the objects array.)
Edit: as a workaround I have now done this:
var keys = Object.keys(this.objects);
keys.forEach(element => {
this.objectsWithKeys.push({
object: this.objects[element],
key: element
});
});
<CustomComponent
v-for="objectWithKeys in objectsWithKeys"
:key="objectWithKeys.key"
:object="objectWithKeys.object"
>
</CustomComponent>
this.$vnode.key
This is solved, I used var objectsWithKeys = data[Object.keys(data)]; and {{ $vnode.key }}.

Javascript - Push an Array into array in object

I have problem to push some value that assigned to be an array in the object
Here my code :
var hasil = [{ product: 'listBarang[i][0]',
shoppers: [],
leftOver: 'listBarang[i][2]',
totalProfit: 0
}]
What I think is using push method like below
hasil.shoppers.push('test')
But it give me an error like this
TypeError: Cannot read property 'push' of undefined
Is anyone know how to deal with this?
hasil is an array of objects, so if you want to maniputate on those objects, you need to access them directly i.e. with hasil[0]:
hasil[0].shoppers.push('test')

Deleting previous items in object when iterating over data Javascript

Outside my scope I have:
var imageData = {};
Then I iterate over my data with jQuery .each like such:
$.each(imgData, function(imagesI) {
imageData = imagesI.QuoteImage;
console.log(imagesI);
})
So when I console log imagesI I get back so many objects (it's different each time) for example my console log looks like;
Object {theImage: "select_q26", Info: "Some info", InfoMeaning: "Info Meaning"}
However, whenever I console.log my object outside which is imageData I only ever get the last object I get from iterating over my data.
Is there anyway to add each object I get back to the variable above without overriding the last one I added?
Thanks!
You could use an array and push the values to that
var imageData = [];
$.each(imgData, function(imagesI) {
imageData.push( imagesI.QuoteImage );
});

Convert array of objects to object

In my node REST application I have a function that queries a database for several records and returns an array of objects.
Since I want it to return a JSON object, I need a way to convert the array of objects to a single object with all the records inside.
Unfortunately I can't find an example on the internet about doing something like this.
Any help would be appreciated.
Why would you want to do that ? Its totally fine to JSON stringify an Array of items, you'll get a structure like
"[{},{},{},...]"
that is probably even an advantage, because you keep the order of items guaranteed.
See the object function of underscore.js.
Lets assume you have an array of objects with the form:
log {
name: "foo",
log: "bar"
}
Your could do:
var logs,//Array of logs
logObj = {}
for(i=0, i<logs.Length i++) {
logObj[logs[i].Name] = logs[i].log;
}
After the loop logObj should be:
logObj {
foo: bar,
nextName: cool comment,
etc.
}

How do I add one single value to a JSON array?

I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];

Categories

Resources