How to convert JavaScript Array to elements - javascript

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)

Related

How do i create a new array with new properties from an existing array

I am trying to create a new list from an existing list messages. for a partically reason the reason i am doing this is to be able to pass this new list into a react component, and that react component is expecting an object that has the value of id and name, and not what the properties of the existing list are (messageId, and messageName)
I have tried the below amount however the below does not work and i get expected Expression statement is not an assignment or call.
const newItems = []
newItems.push(messages.map(message => {
id: message.messageId;
name: message.messageName
}))
There are these issues:
When using the arrow function syntax, the opening brace of (what you intend to be) the object literal is interpreted as the start of a statement block. To avoid this, wrap the literal in parentheses.
In an object literal the properties should not be separated by semicolon, but by colon
.map returns the array, so if you push that array to newItems, the latter will have just one entry: an array. Instead you just need the returned array to be assigned to newItems -- without push
So:
const messages = [{messageId: 1, messageName: "Hello"},{messageId: 2, messageName: "World"}];
const newItems = messages.map(message => ({
id: message.messageId,
name: message.messageName
}));
console.log(newItems);

Why can't array elements use push methods in JavaScript?

var strArr = []
strArr[0].push("someThing Text")
console.log(strArr)
Error: Cannot read properties of undefined (reading 'push')
var strArr = []
strArr[0] = "someThing Text"
console.log(strArr)
Array ["someThing Text"]
What's the difference between the two? Why can't array elements use push methods?
You are trying to push into an array at index 0 inside another array.
var strArr = []
strArr.push("someThing Text")
console.log(strArr)
If you wanted your code to work, you would need to do this.
var strArr = [ [] ] // an array in an array
strArr[0].push("someThing Text")
console.log(strArr)
Simply put, push is an array method. that means it only applies to an array (I look forward to a correction as I am a learner too).
Therefore, push will only apply/operate on an array element if the element is an array as well. Another way to grasp this is to note that elements in an array may be of different data types. Each data type has a different (predefined) set of operations/methods that can be applied to them. push is a predefined method that can be applied only to an array or array element(s) that is/are of the type array.
See the snipped below:
const myArr = ['Hello', 'World', ['Javascript', 'Python', 'PHP'], 100, 'function'];
console.log('Orginal array --> ' + myArr); // Orginal array: Hello,World,Javascript,Python,PHP,100,function
myArr.push(['Vue', 'Angular', 'React']);
console.log('Updated array --> ' + myArr); // Updated array --> Hello,World,Javascript,Python,PHP,100,function,Vue,Angular,React
myArr[2].push('Java');
console.log('Update myArr[2] ' + myArr); // Update myArr[2] Hello,World,Javascript,Python,PHP,Java,100,function,Vue,Angular,React
When you call an array function, you need to call it on the array itself, i.e. strArr.push("someThing Text"). strArr[0] is an array element, and could be a number, string, boolean, or other data type.
You can however add an array element at a specific point in an array, which is sort of what it looks like you were trying to do, with Array.splice(). The parameters are:
index where array element should be inserted
number of items (starting at index) you want to delete
the actual elements you want to insert
var strArr = ["foo", "bar"]
strArr.splice(1, 0, "someThing Text")
console.log(strArr)
You are using the push method on an array element, not the array.
You should use strArr.push()
You are trying to add the element in a specific position using push() method. But the push() method is used to add one or multiple elements to the end of an array. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.
array.push(objectName)
var strArr = []
strArr.push("someThing Text")
console.log(strArr)

Convert Array's into Individual Values in .forEach()

working on a data transformation project that is taking queries from five different databases, and merge them together. (There are two record sets that are very similar to each other and another set of two that are similar to each other.)
Three of five returned records are fine. The other two (which are similar) are oddly returning certain fields as arrays instead of just single values.
i.e.:
dbRecords = [
{
FirstName: ['john', 'john doe']
}
]
it's definitely due to poor data maintenance, but I want to convert these to single values and I was thinking I could do it something like this.
dbRecords.forEach((item, index, arr) => {
Object.keys(item).forEach(i => {
if(i instanceof Array){
item = item[0];
}
}
});
Would that do the trick?
Would that do the trick?
No, cause item is the object and not the value you want to change, you would have to do:
item[i] = item[i][0];
And additionally, i is always a string and never an Array the check must be:
if(item[i] instanceof Array){
And then you would have to store it back to the db.
PS: i is a bad variable name, why dont you just take key or something similar?
"Three of five returned records are fine. The other two (which are similar) are oddly returning certain fields as arrays instead of just single values."
From that statement, it sounds like you know precisely which two fields are the unexpected arrays. In that case, you shouldn't use a loop, but rather target those fields directly.
So assuming the fields are FirstName and LastName, you can do it like this:
dbRecords = dbRecords.map(({FirstName:[FirstName], LastName:[LastName], ...rest}) =>
({FirstName, LastName, ...rest})
);
This takes advantage of parameter destructuring and "rest sytnax" in object literals to extract the first array member two fields that interest you, as well as the rest of the fields into a separate object, then returns a new object with the extracted values along with the rest of the fields.
Here's a working example:
let dbRecords = [{
FirstName: ['john', 'john doe'],
LastName: ['doe', 'john doe'],
OtherField: "foobar"
}, {
FirstName: ['bob', 'bob smith'],
LastName: ['smith', 'bob smith'],
OtherField: "raboof"
}];
dbRecords = dbRecords.map(({FirstName:[FirstName], LastName:[LastName], ...rest}) =>
({FirstName, LastName, ...rest})
);
console.log(dbRecords);

How to reference an object array item using string? [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
I have an array
fruit={sweet:'apple',dry:{f1:'raisin',f2:'almond'},sour:'strawberry'}
it contains simple and nested objects as items
i can reference f1 using bracket notation like fruit[0]["dry"]["f1"]
but i have a string variable that has the value var str="dry.f1"
value of "str" changes on runtime it could be "sweet" or "dry.f1" or "sour"
how do i reference the array item using "str"
if the value of str is either "sweet" or "sour" fruit[str] works fine
we can get the value of f1 using fruit[0].dry.f1 but i need to access it using the variable str
You can use split and reduce:
var fruit={sweet:'apple',dry:{f1:'raisin',f2:'almond'},sour:'strawberry'};
var str1 = "dry.f1";
var str2 = "sweet";
var example1 = str1.split('.').reduce((a, b) => a[b], fruit);
var example2 = str2.split('.').reduce((a, b) => a[b], fruit);
console.log(example1);
console.log(example2);
This will split your string on each dot into an array, and then reduce the fruit array by iterating through the values from the string, applying them to the fruit array, to get the value you are looking for.
Given array:
fruit={sweet:'apple',dry:{f1:'raisin',f2:'almond'},sour:'strawberry'}
And your string:
var str="dry.f1"
To lookup value fruit.dry.f1 you essentially need to write a parser for "dry.f1"
There are plenty of libraries out there that solve this. I give an example below.
AngularJS
Examples of such parsers exist e.g. angular 1.x's $parse: https://docs.angularjs.org/api/ng/service/$parse
var getter = $parse('dry.f1');
var setter = getter.assign;
var context = {sweet:'apple',dry:{f1:'raisin',f2:'almond'},sour:'strawberry'}
expect(getter(context)).toEqual('raisin');
Lodash
Lodash has a get method: https://lodash.com/docs/4.17.4#get
You could make a conditional, if statement that checks if the string has a dot using str.indexOf('.') and do either
fruit[str]
Or
fruit[str1][str2]
In order to access a value in an object given it's path, we must write a function that searches for that value path inside of the object.
Using split and reduce, we use split to break the path into an array of values that were dot-separated in the path (i.e. "dry.f1" becomes ["dry", "f1"]). We then use reduce to iterate over these values in the array, getting deeper into the object in each iteration until we have our value:
function findValueByPath(obj, path) {
return path.split(".").reduce(function(objSoFar, currPath) {
return objSoFar[currPath];
}, obj);
}
For example, findValueByPath( {a: { b: 5 } } , "a.b") returns 5.
Click here to read more about reduce.
Click here to read more about split.
As a side note, this problem is commonly implemented by libraries such as Lodash, which has the function get that does exactly this (click here for get documentation in Lodash).

Initialize an array whose indexes are scattered over integer range

How to initialize a string array (size<100 items) in javascript whose indexes are scattered over entire integer range, with data items.
If I do like this:
array1 = ["string1","string2","string3","string4"];
then I get array of length 4 with indices ranging 0 to 3
But in my case i want to keep my own indices, so that the array could be used like a high performance int-string hash table.
I'm preferably looking out for a single statement initialization.
The items of the array should be accessible like this: array1[23454]
Update From Comments
I'm restricted to initialize the array as a single statement since a dynamically prepared array initialization string is appended from server side like this: var array = <string from server here>
To create an array with a set number of indexes you can use
// Creates an array with 12 indexes
var myArray = new Array(12);
This isn't needed in javascript due to the way its array's work. There isn't an upper-bound for arrays. If you try to reference an item index in the array that doesn't exist, undefined is returned but no error is thrown
To create an array with perscribed indexes you can use something like array['index'] = value though this would force you to use multiple statements. Javascript doesn't have an array initalizer to allow for you to specify indexes and values all in a single statement though you can create a function to do as such
function indexArray(param) {
var a = [], i;
for (i=0; i<param.length; i+=1) {
a[param[i].index] = param[i].value;
}
return a;
}
var myArray = indexArray([
{ index: 123456, value : "bananas" },
{ index: 12, value : "grapes" },
{ index: 564, value : "monkeys" }
]);
var array1 = []
array1[23454] = 2
Just doing this should be fine. There's no set array size for javascript in the way there is for java.
If you really want to do this all in a single statement, you can make an object instead like this:
var object1 = {
"23454":2,
"123":1,
"50":3
};
and then retrieve the numbers like this:
object1["23454"] //2
I don't really recommend this though. The array method is a cleaner way of doing it even if it takes multiple lines since it doesn't require string conversion. I don't know enough about how these are implemented in browsers to comment on the performance impact.
Update
Since the 1 line requirement is based on something being passed to the server, I would recommend passing a JSON object to the server in the form:
"{"23454":2,"123":1,"50":3}"
then this code will parse it to an object:
var object1 = JSON.parse(jsonstringfromserver);
and if you like you can always convert that to an array by enumerating over the properties with a for in loop:
var array1 = []
for ( num in object1){
array1[num] = object1[num];
That is probably unnecessary though since object1[123] will already return 1. You only need this if you plan on doing array specific operations.
You don't have to pre-define the size of an array before you assign to it. For example:
var _array = [];
_array[0] = "foo";
_array[1000] = "bar"; // _array.length => 1001
_array[1] //undefined
No need to initialise the appropriate number of array elements before you assign to them.
Update
It already has been pointed out that you can use an object rather than an array. However, if you want to take advantage of array methods then this is still possible. Let me give you an example:
var obj = {
0: 15,
1: 10,
2: 5,
length: 3
};
If the object contains a length property then it can be treated as an array-like object. Although you can't call array methods directly from these objects you can use array methods.
Array.prototype.join.call( obj ); // 15,10,5
In fact using the ECMAScript 5 map function you can easily convert the above object to an array.
var _array = Array.prototype.map.call( obj, function( x ) { return x; } );
The map function does not exist in all browsers but you can use the following function if it doesn't.
Array.map = Array.map || function(a, f, thisArg) {
return Array.prototype.map.call(a, f, thisArg);
}
You can do what you want with an Object in this way:
var o = {23454: 'aaaa', 23473: 'bbb'};
You will lose the array methods/fields, e.g. length, but you will gain what you said you are looking for, and you will be able to add/remove members easily.

Categories