How to create and populate an array programmatically - javascript

I am trying to create a multi dimensional array programmatically. But when i push an object into the array it gets pushed into all indexes in the array. Why is this happening
Here's a simple demo
let postTest = new Array(4).fill([]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);

Use Array.from instead, Array.prototype.fill copies the reference of object on all places so any change at one place will reflect at all places
let postTest = Array.from({length: 4}, ()=> []);
postTest[0].push({ key: 'value', anotherKey: 'value' });
console.log(postTest);

As mentioned in the fill() method docs:
value
Value to fill the array with. (Note all elements in the array will be this exact value.)
You can fix this issue, by assigning the empty array to individual index using .map() so that there no reference issue like:
let postTest = new Array(4).fill().map(x=>[]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);
You can also, try:
let postTest = [...Array(4)].map(x=>[]);
postTest[0].push({key: 'value', anotherKey: 'value'});
console.log(postTest);

Related

Nested object in Javascript array

JS noob here. I want to store a list of option for a dropdown in an array. I want a key to be associated with every value something like this
var newArray = [
{
key: "key",
val:({value:"val", label:"label"}, {value:"val",label:"label"})
}
]
The code above returns undefined when I try to read val. What is the solution? Thanks
var newArray = [
{
key: "key",
val:[{value:"val", label:"label"}, {value:"val",label:"label"}]
}]
The only thing i changed were parentheses () into [], because it's the thing that declares an array. Now, if you want to read the val key, you need to do this stuff.
You have an array named "newArray". It only has 1 element (which is also the first).
Now lets get the first element of the array by newArray[0]. Now you have accessed the object inside the array. Now you can read the the value by newArray[0].val. And now you have entered a new array, which elements you can read with newArray[0].val[0] and newArray[0].val[1]

How to convert JavaScript Array to elements

I have an Array
var fieldsToFetch = ['name', 'class', 'rollNumber'];
I am using this array into NODE-ORM2 query, in simple words, I am saying to ORM that this are the fields I want to fetch.
Person.find({ surname: "Doe" }).limit(3).offset(2).only("name", "class", "rollNumber").run(function (err, people) {
// returning only 'name', 'rollNumber' and 'class' properties
//this is working fine
});
In this code, you can see the .only() function which takes the field names. If I am passing the name here by comma separating then it is working fine but if I do like this
Person.find({ surname: "Doe" }).limit(3).offset(2).only(fieldsToFetch).run(function (err, people) {
// returning only 'name', 'class' and 'rollNumber' properties
// not working
});
I also tried
String(fieldsToFetch ); and fieldsToFetch .toString(); but it converts whole array into a single string. So how can I use this array as a parameter here?
Thankyou.
EDIT
Passing 2 or 3 parameter is not a challenge the main goal is to get all array element as individual elements.
Because you pass an array, but it want separate strings, so if you use ES6 you can pass like .only(...fieldsToFetch).
This is called spread operator. It gets the array, splits it into items and passes them as separate parameters.
Example
function f(a,b,c){
console.log(a);
console.log(b);
console.log(c);
}
var args = [1,2,3];
f(...args);
I pass the array with the spread operator and it splits the array into separate items and assigns to the parameters in direction from left to right.
Try like this..use array.splice() to remove last element from array.Then use ... spread operator:
var fieldsToFetch = ['name', 'class', 'rollNumber'];
fieldsToFetch.splice(2,1);//now array having two elements ['name', 'class']
then
.only(...fieldsToFetch)

Json array appending a object

i have pushed data to an array like this
this.data.push{'data': 'type',
'value': 'apple'}
and i want to append the value of that particular array's value object. I tried to do it like this
this.data[index].value.push = 'banana';
but it doesn't work?? I want to replace the value
Push is a function Array.push()
this.data[index].push('banana');
Adding items to arrays work like this in javascript:
this.data.push({'data': 'type', 'value': 'apple'});
However, given that your data is an object, you don't need to use push:
this.data[index].value = 'banana';
You can access a value from a javascript object directly.
Given that you have used string keys, you will probably have to do the following:
this.data[index]['value'] = 'banana';
Look at this for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
i have pushed data to an array like this
this.data.push{'data': 'type', 'value': 'apple'}
No! That does not work without getting a syntax error.
You could use
this.data.push({'data': 'type', 'value': 'apple'});
for inserting a new object at the end of the array data.
For changing a specific objects's property, you need to assign the new content, like
this.data[index].value = 'banana';
This takes an element and the property and assigns the new value 'banana' to it.
Please have a look to properties accessors for objects, like
object.property
object["property"]
make it
this.data[index].value = ['banana'];
since you need to replace the value of value attribute with an array.
If this needs to be repeated again then
Array.isArray(this.data[index].value) ? (this.data[index].value = ['banana']) : this.data[index].value.push('banana');
push takes a parameter of object, you must have pass this parameter in braces
this.data.push({'data': 'type', 'value': 'apple'})
to change value you can directly change field value
this.data[index].value = 'banana';
if you want to keep multiple values in value then make value an array as well.

Javascript get value from an object inside an array

I have an object with key value pairs inside an array:
var data = [
{
"errorCode":100,
"message":{},
"name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"value":"2"
}
];
I want to get the value of "value" key in the object. ie, the output should be "2".
I tried this:
console.log(data[value]);
console.log(data.value);
Both logging "undefined". I saw similar questions in SO itself. But, I couldn't figure out a solution for my problem.
You can use the map property of the array. Never try to get the value by hardcoding the index value, as mentioned in the above answers, Which might get you in trouble. For your case the below code will works.
data.map(x => x.value)
You are trying to get the value from the first element of the array. ie, data[0]. This will work:
console.log(data[0].value);
If you have multiple elements in the array, use JavaScript map function or some other function like forEach to iterate through the arrays.
data.map(x => console.log(x.value));
data.forEach(x => console.log(x.value));
data is Array you need get first element in Array and then get Value property from Object,
var data = [{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}];
console.log(data[0].Value);
Try this...
Actually Here Data is an array of object so you first need to access that object and then you can access Value of that object.
var data = [
{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}
];
alert(data[0].Value);
what you are trying to read is an object which an element of an array, so you should first fetch the element of array by specifying its index like
data[0] and then read a property of the fetched object, i.e. .value,
so the complete syntax would be data[0].value
Hope it helps !

How to update an object property array value?

If I have an object defined as:
var myObj={};
Then, I update this object with:
myObj['fruit']=['apple', 'orange'];
Later, I would like to append "[banana, melon]" to myObj['fruit'], that's update myObj to
['apple','orange','banana','melon']
what is the most elegant way to update 'fruit' attribute value of myObj in my case? That's update array by appending a new array.
--------EDIT-------
I need a way to append array as one variable, not extract each element of the appended array and push. e.g. oldArray append with newArray = final array
JavaScript has a built in Array.push()
myObj["fruit"].push( 'banana', 'melon' );
There are a few ways to approach appending an array. First up, use apply() to call push with the array as individual arguments:
var toAppend = ['banana', 'melon'];
// note [].push is just getting the "push" function from an empty array
// the first argument to "apply" is the array you are pushing too, the
// second is the array containing items to append
[].push.apply( myObj["fruit"], toAppend );
Also, you could concat() the arrays, however concat doesn't modify the original array so if you have other references they might get lost:
myObj["fruit"] = myObj["fruit"].concat( toAppend );
If you don't want to push, then concat :)
I would suggest to iterate the array items that you want to push, by doing this:
var newObj = ["banana", "melon"];
for (var i in newObj)
{
myObj['fruit'].push(newObj[i]);
}
:)

Categories