JavaScript: Convert array to object without key or string - javascript

I have an array like [1,2,3,4,5]. I want to convert it to object like {1,2,3,4,5} or 1,2,3,4,5.
I would be thankful if someone helps me.

for 1,2,3,4,5, you just have to use .join()
const arr = [1,2,3,4,5]
console.log(arr.join())
Also, specifically for query parameters, in browser or Node, you could use URLSearchParams, which helps you define your query object
const obj = { a: [1,2,3,4,5] }
const searchParams = new URLSearchParams(obj).toString();
console.log(searchParams)

Related

JavaScript: How to convert a string to a 2D array

I have a String value as input that contains a 2-dimensional array in the following format:
"[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"
Also, I need to build the actual multidimensional array and store it in a new variable.
var arr = [[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]];
I know I can traverse the String or even use Regular Expressions to build the array. But I wonder if there is any function similar to eval() in Python to convert the String to an equivalent JS array object directly (despite being a slow process).
var arr = eval("[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]");
Considering you have it stored like this
let x = "[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"
let arr = JSON.parse(x)
You array is a valid json that can be parsed and manipulated
let x = "[[1,0,1,1],[0,1,0,1],[1,0,1,1],[0,1,0,1]]"
let arr = JSON.parse(x);
console.log(arr)
Beware that if the string is not a valid json the above code will fail

javascript merge to array with name

I am new in JS. It is a simple task but find it is hard to solve. I tried many methods includingconcat,push,$.merge
Here is an example
var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
I want to get a result like [a:"b", c:"d", e:"f", g:"h"],
Here is some method I have tried
a.concat(b)get []
a.push(b) get 1
$.merge(a,b) get [0:[e:"f", g:"h"],a:"b",c:"d"]
I don't know where to go, Please help
The biggest problem you're running into right now is that you are trying to use an array as an object, so first when you're initializing a and b you should use curly braces instead. And then to merge them, you can use the spread operator: ....
All of that culminates into this:
let a = {};
let b = {};
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
a = {...a, ...b}
You cant get an array with key-value pairs its an invalid syntax, but you can create an object. Just spread both of your objects into an single object:
var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
let result = {...a,...b};
console.log(result);

Creating a hash of data JS

I have some data set represented as array, which i want to put in an object as property. I want each property to be accessible by generated key. Number and type of elements in array is unknown. I want it to look something like that:
// array - array on unknown data
let object = {};
object[createUniqueKey(array)] = array;
// and later i want to use it the same way
console.log(object[createUniqueKey(array)])
Hope i've described well, thanks for help in advance
The easiest way to create a unique key to avoid having your object's data overwritten is to use a counter and increment it on every insertion. Alternatively, you could implement your own UUID-generating function, but I wouldn't go as far.
Example:
let object = {};
let createUniqueKey = ((counter) => () => counter++)(0);
let array = ["a", "b", "c"];
/* Create a unique key. */
let key = createUniqueKey();
/* Create a unique key to store the array. */
object[key] = array;
/* Use the key to get the array from the object. */
console.log(object[key]);
If instead, you want to use the array and based on that to create your key, the only solution that comes to my mind now is using a combination of toString and btoa (or simply the latter as it accepts array arguments). However, this method has some restrictions such as when the array contains objects and functions.
Example:
let object = {};
let createKey = (array) => btoa(array);
let array = ["a", "b", "c"];
/* Create a key to store the array. */
object[createKey(array)] = array;
/* Use the array to recreate the key and access the array inside the object. */
console.log(object[createKey(array)]);

How to convert Map keys to array?

Lets say I have the following map:
let myMap = new Map().set('a', 1).set('b', 2);
And I want to obtain ['a', 'b'] based on the above. My current solution seems so long and horrible.
let myMap = new Map().set('a', 1).set('b', 2);
let keys = [];
for (let key of myMap)
keys.push(key);
console.log(keys);
There must be a better way, no?
Map.keys() returns a MapIterator object which can be converted to Array using Array.from:
let keys = Array.from( myMap.keys() );
// ["a", "b"]
EDIT: you can also convert iterable object to array using spread syntax
let keys =[ ...myMap.keys() ];
// ["a", "b"]
You can use the spread operator to convert Map.keys() iterator in an Array.
let myMap = new Map().set('a', 1).set('b', 2).set(983, true)
let keys = [...myMap.keys()]
console.log(keys)
OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:
The Map object holds key-value pairs and remembers the original
insertion order of the keys.
Any value (both objects and primitive
values) may be used as either a key or a value.
As you mentioned, you can easily create an instance of Map using new keyword...
In your case:
let myMap = new Map().set('a', 1).set('b', 2);
So let's see...
The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...
Map has many methods which you can use, like set() which you already used to assign the key values...
One of them is keys() which returns all the keys...
In your case, it will return:
MapIterator {"a", "b"}
and you easily convert them to an Array using ES6 ways, like spread operator...
const b = [...myMap.keys()];
I need something similiar with angular reactive form:
let myMap = new Map().set(0, {status: 'VALID'}).set(1, {status: 'INVALID'});
let mapToArray = Array.from(myMap.values());
let isValid = mapToArray.every(x => x.status === 'VALID');
Not exactly best answer to question but this trick new Array(...someMap) saved me couple of times when I need both key and value to generate needed array. For example when there is need to create react components from Map object based on both key and value values.
let map = new Map();
map.set("1", 1);
map.set("2", 2);
console.log(new Array(...map).map(pairs => pairs[0])); -> ["1", "2"]
Side note, if you are using a JavaScript object instead of a map, you can use Object.keys(object) which will return an array of the keys. Docs: link
Note that a JS object is different from a map and can't necessarily be used interchangeably!

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