Push object into array without key in javascript - javascript

I want to push my object without a key in my javascript array. Right now the issue is I psuh my object in the array, but I add extra key 0,1,2 ... I don't want that key. Is there any solution for that? Here I add the code that I implemented.
let newArr = [];
let myId = data['id'];
var key = myId;
var obj = {};
myobj[key] = {
data: "testdata"
};
newArr.push(myobj);
The above code generates output like below. I don't want that 0 key in my array
0: {
260: {
data: 'testdata'
},
}

It's hard to tell what you're wanting, but I expect you don't want to be using an array here at all? You just want a single object that contains all of your key-value pairs?
e.g. something like this:
const data = { id: 1234 };
let myId = data['id'];
var key = myId;
var myobj = {};
myobj[key] = {
data: "testdata"
};
console.log(myobj);
// You can then add more data
myobj[2345] = {
data: "more test data"
};
console.log(myobj);
// Example Property Access
console.log(myobj[2345])

Try this
newArr.push(...myobj);

Related

get object name returned in a string

Say I have a code like this:
var object = {
property_1:'value_1'
}
var arr = [object]
I want to be able to get an object name returned as a string. So it would look something like this:
arr[0].name /*return 'object'*/
or
arr[0].property_1.objectName /*return 'object'*/
This obviously isn't a valid code, but is there any that could actually do this?
It's not possible to do what you want. However, you could do the following:
var objects = {
object1: {
property_1:'value_1'
},
object2: {
property_1:'value_2'
}
};
// Use this to get an array with the names
function getNames() {
return Object.keys(objects);
}
// Use this to get the properties of an object by it's given name
function getProps(name) {
return objects[name];
}
Execution example:
var names = getNames();
for(i = 0; i < names.length; i++) {
var name = names[i];
var values = getProps(name);
console.log(name);
console.log(values);
console.log(values.property_1);
}
Output:
object1
{property_1: "value_1"}
value_1
object2
{property_1: "value_2"}
value_2
All this considering you are using ES5.
With ES6 you could simply do the following to get a list of object names and properties:
Object.keys(objects).map(key => ({name: key, properties: objects[key]}))
I hope this helps you in some way!
is there any that could actually do this?
No. var object is not what you are assigning to the array, the content of it is what you assigned.
var object = {
property_1:'value_1'
}
var arr = [object]
Is the same as:
var object1 = {
property_1:'value_1'
}
var object2 = object1;
arr = [object2];
and in the second example object1, object2 and arr[0] all point to the same object, and that object has no name.

Converting object containing list of data to json array

My for loop looks like this,
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(myObj[key]);
}}
output on console looks like this,
car1
car2
car3
i want to convert this data something like this,
$scope.myArray = [{"cars":car1}, {"cars":car2}, {"cars":car3}]
how can I convert it this way in javascript?
You can use var json = JSON.stringify(jsObject) and var jsObject = JSON.parse("json string")
Just iterate over object and push it into array:
var myObj = data.response.carTypes;
var myArr = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
myArr.push(myObj[key]);
}
}
console.log(myArr);
You can convert the array to JSON using var myJsonArray = JSON.stringify(myArray).
If you're doing this conversion in an older browser, you can use a script.
In order to get your array from the JSON you created, you can use:
var myArray = JSON.parse(myJsonArray)
Also, bear in mind that when you use the same key for several objects in your JSON, the last key with the same name is the one that is going to be used.
Here you have to use javascript object.
say
$scope.myArray = [];
var carlist.cars="";
var carlist={};
carlist is a object which cars is a property
then you can try this way:
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carlist.cars=myObj[key];
myArray.push(carlist);
console.log(myArray);
}}
You just need to create a new array and push a new object to it in each iteration:
$scope.myArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
$scope.myArray.push({cars:myObj[key]});
}
};
Demo:
var myObj = {
a: "Car1",
b: "Car2",
c: "Car3"
};
var carsArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carsArray.push({cars:myObj[key]});
}
};
console.log(carsArray);

How to make another nested json with keys from a nested json

The strings that are coming from source is coming in fragmented JSON object in JSON object.I want to convert this JSON structure to a another simple JSON structure:
{
"nestA":{
"a":"link",
"b":2711
},
"nestB":{
"a":"img",
"b":4165
}
}
could it changed to be like
{
"key":"nestA"
"a":"link"
"b":711
},
{
"key":"nestB"
"a":"img"
"b":165
}
//convert json string into an object
var json = '{"nestA":{"a":"link","b":2711},"nestB":{"a":"img","b":4165}}'
var sourceObject = JSON.parse(json);
//get a list of the object keys
var keys = Object.keys(sourceObject);
//create a new array to hold our output
var array = [];
//loop through our keys adding them to our array in the format we want
keys.forEach(function(key){
var nest = sourceObject[key];
nest.key = key;
array.push(nest);
});
//convert our array back to json
var result = JSON.stringify(array);
console.log(result);
var json = [{
"nestA":{
"a":"link",
"b":2711
},
"nestB":{
"a":"img",
"b":4165
}
}];
var arr = [];
json.forEach(function(v) {
Object.keys(v).forEach(c => arr.push(v[c]));
arr.forEach((b, x) => b['key'] = Object.keys(v)[x]);
});
console.log(arr);
Working with JSON it's best to parse it first, modify it and then turn it back into JSON:
var orgObj = JSON.parse(orgJSON);
var newArr = [];
for( var key in orgObj){
var temp = { key: key };
Object.assign( temp, orgObj[key]);
newArr.push(temp);
}
var newJSON = JSON.stringify(newArr);
Assuming an array was what you were going for. Please clean up your desired JSON.
Without using es6 the for loop could be:
for( var key in orgObj){
orgObj[key].key = key;
newArr.push( orgObj[key] );
}
but orgObj would get modified.

Constructing an array from JSON

I'm getting a JSON using
$.getJSON("http://localhost:8080/test_json/", function(data) {
});
Output looks like this.
{"items":[{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}]}
After some trimming
data = JSON.stringify(data);
data = data.substring(9);
data = data.substring(0, data.length - 1);
data = data.replace(/[{}]/g, " ");
console.log(data);
It looks like this
["1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7]
I would like to "deconstruct" (?) this as to remove all keys so that only values remain.
[1 ,2 ,3 , 4 , 5 , 6 ,7]
I'm going to use this to draw charts. So for exampel that could be my data that I'm going to pass to my chart library.
Please don't start "trimming" your JSON like that. Just parse it and process it like any other object.
var json = '{"items":[{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}]}';
Parse your JSON to a JS object (tho I note that you're using jQuery to get the data so this will be parsed already, so you can skip this step):
var obj = JSON.parse(json);
Grab the first element of items (an array) which is an another object:
var items = obj.items[0];
Grab the item keys with Object.keys() and use that array to return the values with map.
var vals = Object.keys(items).map(function (el) {
return items[el];
}); // [ 1, 2, 3, 4, 5, 6, 7 ]
DEMO
EDIT
So now you have some new data:
var json = '{"items":[{"sum":188700.75},{"sum":633927.98},{"sum":7000},{"sum":65169.26},{"sum":17114.67},{"sum":252340.96},{"sum":1073246.73}]}'
The following JS will grab the value of sum from each object:
var items = obj.items;
var vals = items.map(function (el) {
return el.sum;
});
Output
[ 188700.75, 633927.98, 7000, 65169.26, 17114.67, 252340.96, 1073246.73 ]
DEMO
You have json data why need stringify it ?
var input = data.items[0]
var arr = $.map(input,function(v){
return v;
});
First, if you want to extract the values, you can do it by accessing it like this:
var obj = data.items[0];
Your variable obj will look like this:
{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}
Then I guess you will have to iterate on this object to make it an array:
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
The variable arr will then contain the elements you wish.
DEMO
A different approach from what have been told you.
You don't need to trim the data.
var json = JSON.parse(data);
var items = json.items[0];
And you don't need to remove keys, you can send the values into another array.
var listOfItems = [];
for(var key in items)
listOfItems.push(items[key]);

Adding elements to object

I need to populate a json file, now I have something like this:
{"element":{"id":10,"quantity":1}}
And I need to add another "element". My first step is putting that json in a Object type using cart = JSON.parse, now I need to add the new element.
I supposed I must use cart.push to add another element, I tried this:
var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);
But I got error "Object has no method push" when I try to do element.push, and I think I'm doing something VERY wrong because I'm not telling the "element" anywhere.
How can I do that?
Edit: sorry to all I had a LOT of confusion in my head.
I thought I can get only object type when taking data from JSON.parse, but I get what I put in the JSON in the first place.
Putting array instead of object solved my problem, I used lots of suggestions got here too, thank you all!
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
JSON.stringify() was mentioned as a concern in the comment:
>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
The line of code below defines element as a plain object.
let element = {}
This type of JavaScript object with {} around it has no push() method. To add new items to an object like this, use this syntax:
element[yourKey] = yourValue
To put it all together, see the example below:
let element = {} // make an empty object
/* --- Add Things To The Object --- */
element['active'] = true // 'active' is the key, and 'true' is the value
console.log(element) // Expected result -> {type: true}
element['state'] = 'slow' // 'state' is the key and 'slow' is the value
console.log(element) // Expected result -> {type: true, state: 'slow'}
On the other hand, if you defined the object as an array (i.e. using [] instead of {}), then you can add new elements using the push() method.
To append to an object use Object.assign
var ElementList ={}
function addElement (ElementList, element) {
let newList = Object.assign(ElementList, element)
return newList
}
console.log(ElementList)
Output:
{"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}
If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:
var element = { quantity: quantity };
cart[id] = element;
This allows you to add multiple items to the cart like so:
cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};
// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }
Adding new key/pair elements into the original object:
const obj = { a:1, b:2 }
const add = { c:3, d:4, e: ['x','y','z'] }
Object.entries(add).forEach(([key,value]) => { obj[key] = value })
obj new value:
{a: 1, b: 2, c: 3, d: 4, e: ['x', 'y', 'z'] }
I was reading something related to this try if it is useful.
1.Define a push function inside a object.
let obj={push:function push(element){ [].push.call(this,element)}};
Now you can push elements like an array
obj.push(1)
obj.push({a:1})
obj.push([1,2,3])
This will produce this object
obj={
0: 1
1: {a: 1}
2: (3) [1, 2, 3]
length: 3
}
Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push() function
you should write var element = [];
in javascript {} is an empty object and [] is an empty array.
cart.push({"element":{ id: id, quantity: quantity }});
function addValueInObject(object, key, value) {
var res = {};
var textObject = JSON.stringify(object);
if (textObject === '{}') {
res = JSON.parse('{"' + key + '":"' + value + '"}');
} else {
res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
}
return res;
}
this code is worked.
Try this:
var data = [{field:"Data",type:"date"}, {field:"Numero",type:"number"}];
var columns = {};
var index = 0;
$.each(data, function() {
columns[index] = {
field : this.field,
type : this.type
};
index++;
});
console.log(columns);
If anyone comes looking to create a similar JSON, just without using cart as an array, here goes:
I have an array of objects myArr as:
var myArr = [{resourceType:"myRT",
id: 1,
value:"ha"},
{resourceType:"myRT",
id: 2,
value:"he"},
{resourceType:"myRT",
id: 3,
value:"Li"}];
and I will attempt to create a JSON with the following structure:
{
"1":{"resourceType":"myRT","id":"1","value":"ha"},
"2":{"resourceType":"myRT","id":"2","value":"he"},
"3":{"resourceType":"myRT","id":"3","value":"Li"}
}
you can simply do-
var cart = {};
myArr.map(function(myObj){
cart[myObj.id]= myObj;
});
function addValueInObject(value, object, key) {
var addMoreOptions = eval('{"' + key + '":' + value + '}');
if(addMoreOptions != null) {
var textObject = JSON.stringify(object);
textObject = textObject.substring(1,textObject.length-1);
var AddElement = JSON.stringify(addMoreOptions);
object = eval('{' + textObject +','+ AddElement.substring(1,AddElement.length-1) + '}');
}
return object;
}
addValueInObject('sdfasfas', yourObject, 'keyname');
OR:
var obj = {'key':'value'};
obj.key2 = 'value2';
For anyone still looking for a solution, I think that the objects should have been stored in an array like...
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
Then when you want to use an element as an object you can do this...
var element = cart.find(function (el) { return el.id === "id_that_we_want";});
Put a variable at "id_that_we_want" and give it the id of the element that we want from our array. An "elemnt" object is returned. Of course we dont have to us id to find the object. We could use any other property to do the find.
My proposition is to use different data structure that proposed already in other answers - it allows you to make push on card.elements and allow to expand card properties:
let card = {
elements: [
{"id":10,"quantity":1}
],
//other card fields like 'owner' or something...
}
card.elements.push({"id":22,"quantity":3})
console.log(card);
push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below
var lastIndex = Object.keys(element)[Object.keys(element).length-1];
then add object to the new index of element
element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };
if you not design to do loop with in JS e.g. pass to PHP to do loop for you
let decision = {}
decision[code+'#'+row] = event.target.value
this concept may help a bit
This is an old question, anyway today the best practice is by using Object.defineProperty
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
In case anyone else needs this, I finally found a good way to add objects or arrays of objects:
var myobj = {}
// These two options only work for single-valued keys, not arrays or objects
myobj["a"] = 1
myobj.b = 2
// This one works for everyting:
Object.assign(myobj, {"key": "value"}); // single-value
// Add object
Object.assign(myobj, {"subobj":
{
"c": 3
}
});
// Add array of objects
Object.assign(myobj, {"subarr":
[
{
"d": 4,
},
{
"e": 5
}
]
});
var newObject = {element:{"id":10,"quantity":1}};
console.log(newObject);

Categories