javascript merge to array with name - javascript

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);

Related

JavaScript: Convert array to object without key or string

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)

How do I add the same element to an array multiple times?

I'm making shopping cart,and I am a little bit confused. There is a counter which counts number of current product. For example: the user can buy 5 book or more. So , I need to make a function which adds the element аs many times as the user will select it.
I made something like this:
[...state.shoppingCart, new Array(state.booksNumber).fill({...action.book})]
But of course it makes a new array in array... So how can I just add elements to an array without deleting old elements or creating a new array inside the array?
I need a functional way, no loops.
const newArray = new Array(state.booksNumber).fill({...action.book})
[...state.shoppingCart, ...newArray]
Simply use the spread syntax again:
[...state.shoppingCart, ...new Array(state.booksNumber).fill({...action.book})]
That will spread the new array into the existing array.
You can use the concat method
const a = new Array([1,3,4]).concat([1,3,4])
console.log(a)
This will add the elements into the array.
Or you can try with spread operator.
const arr=[1,2,3,4]
const a = new Array([1,3,4,.... arr]);
console.log(a)
You are missing the spread operator inside the returning array for the new Array you created.
Adding the spread operator allows you to merge/concat both array items.
For example:
const arrayOne = [1,2,3];
const arrayTwo = [4,5,6];
const mergedArrays = [...arrayOne, ...arrayTwo] //[1,2,3,4,5,6]
Also assuming action.book is an object you want to add multiple times inside of the new Array() you've created, there is no need to spread it as it will fill the array with each object.
This function might help out with what you are looking for:
const addMultipleItems = (action) => {
const items = new Array(state.booksNumber).fill(action.book);
return [...state.shoppingCart, ...items];
}

How to search in nested JSON data in vuejs?

I have nested JSON data like:
[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]
I want to filter the JSON by province_id and put it in another variable. Is there any solutions in VueJS such as Vue.filter(); ?
I know we have "linq" which does the job but I do not want to use it.
what you're looking for is the javascript Array's filter() function. You should definitely spend some time getting familiar with filter, along with others like map and reduce. It'll make slicing and dicing your data much easier.
var serializedData = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var data = JSON.parse(serializedData);
var provinceAbc = data.filter(d => d.province_id === 'ABC');
That line will get you all objects where its province_id is "ABC"
Also, since you mentioned "linq" in your post, filter() is like IEnumerable.Where(), and map() is like IEnumerable.Select() in .NET Linq terms
I think this will work for you:
var nestedJson = `[{"id":"1","province_id":"ABC","name":"City One"},{"id":"2","province_id":"EFG","name":"City Two"}]`;
var array = JSON.parse(nestedJson);
array = array.map(e => e["province_id"]);
console.log(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!

angularjs : iterate array with key value pairs

I am creating an array like the following:
var arr =[];
arr['key1'] = 'value1';
arr['key2'] = 'value2';
If is use this array in ng-repeat tag, it is not displaying anything. Is there any way to make it work?
<div data-ng-repeat='(key,value) in arr'>{{key}} - {{value}}</div>
Is there any way to make it work?
The way to go, is to creat plain object (instead of array)
// instead of creatin of an Array
// $scope.myArr = [];
// we just create plain object
$scope.myArr = {};
...
// here we just add properties (key/value)
$scope.myArr['attempt1'] = {};
...
// which is in this case same as this syntax
$scope.myArr.attempt1 = {};
Thee is updated plunker
Check more details what is behind for example here:
Javascript: Understanding Objects vs Arrays and When to Use Them. [Part 1]
Your associative array is nothing but an object, as far as JavaScript is concerned. IMO Associative arrays and Objects are almost same.
Ex: Your arr['key1'] = 'value1'; can be called as console.log(arr.key1);
To make your code work, you need to change the array declaration by removing [] and replacing with {} (Curly braces)
Like this var arr = {};

Categories

Resources