How do i assign key / value pairs of an array of strings - javascript

let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']
I'd like to assign key value pairs of the strings i have in the array above
for example:
[{drink: 'soda'},
{name: 'john'},
{someKey:'someValue'}
]
I've spent hours trying to figure this out... I've tried approaching it with the map method but my limited knowledge on javascript is consistently returning errors...
I'd really appreciate it if someone could help me out. Thanks

You can do it with a simple for loop:
let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue'];
let result = [];
for(let i = 0; i < arr.length; i+=2) {
let obj = {}
obj[arr[i]] = arr[i+1];
result.push(obj)
}
console.log(result)

A simple old-school loop increasing the step by 2 on each iteration.
Note: this will give you a single object with key/value pairs which makes (to my mind) a more useful data structure than an array of objects with one key/value pair each. If you're looking for an array of objects #sonEtLumiere's answer is the right one.
const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue'];
// Initialise empty object
const out = {};
// Loop over the array in steps of 2 so
// that we can access `i` (the key) and
// `i + 1` (the value) on each iteration
for (let i = 0; i < arr.length; i += 2) {
out[arr[i]] = arr[i + 1];
}
console.log(out);
console.log(out.drink);
console.log(out.name);
console.log(out.someKey);

That would be the easiest way:
const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']
const obj = {}
for (let i = 0; i < arr.length; i += 2) {
obj[arr[i]] = arr[i + 1]
}
console.log(obj)
Or if you really want a oneliner
const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']
const result = arr.reduce((fin, str, i, arr) => i & 1 ? fin : { ...fin, [str]: arr[i + 1] }, {})
console.log(result)

Related

Update value of object with values in different array

I have two array with below structure:
Array1:
[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
Array2:
[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
result
Array1 =[{id:1234,name:"macaron",quantity:"330gm",rate:"300"},{id:5678,name:"Gelato",quantity:"450gm",rate:"500"}]
I want to be able to update the only rates of objects in Array1 with rate of objects in Array2.
If order or lengths of the arrays are different one efficient way is
create a Map of the new rates from Array2 then loop over Array1 ant get() from the Map.
This way you only iterate Array2 once instead of using multiple iterations of methods like find()
let Array1=[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}],
Array2=[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}];
const rateMap = new Map(Array2.map(({id, rate})=> [id, rate]));
Array1.forEach(e=> rateMap.has(e.id) && (e.rate = rateMap.get(e.id )))
console.log(Array1)
let Array1 = [
{id:1234,name:"macaron",quantity:"330gm",rate:"100"},
{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}
];
let Array2 = [
{id:1234,name:"macaron",quantity:"600gm",rate:"300"},
{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}
];
for (i = 0; i < Array1.length ; i++) {
Array1[i].rate = Array2[i].rate
}
console.log(Array1)
Array1 = Array1.map(item => {
return { ...item, rate: Array2.filter(rec => rec.id === item.id)[0].rate };
});
});
The cleanest solution I came up with.
But as charlietfl said: I make assumtion that both lengths are the same and in same order
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
console.log(this[i].rate)
this[i].rate = array2[i].rate;
console.log(this[i].rate)
}
}
array1.updateRate(array2);
console.log(array1)
Here is second (full) solution, where that asumption isn't made:
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
for(let j = 0; j < array2.lenght;j++) {
if(this[i].id === array2[j].id) {
this[i].rate = array2[j].rate;
break;
}
}
}
}
array1.updateRate(array2);
console.log(array2)

How to group elements of array

I have an array:
var arr = ['User1','123456','User2','456789','User3','546544'];
How can I get array of object like this:
var arr2 = [{name: 'User1', id: 123456},{name: 'User2', id: 456789}, {name: 'User3', id: 546544}];
I tried this:
arr.forEach(function (item, i, arr) {
arr2.push(
{
name: arr[i],
id: arr[i + 2]
}
);
});
In a simple way, you need to do two things:
Check if the length is even.
Push it as how you require, by incrementing the loop twice.
var arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];
var arrObj = [];
if (arr.length % 2 === 0)
for (var i = 0; i < arr.length; i += 2)
arrObj.push({
"name": arr[i],
"id": parseInt(arr[i + 1], 10),
});
console.log(arrObj);
Look at the comments inside the code.
const arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];
// Ok, so what you to do is to group the infos and create a new object
// There is many function you can use, in the following example, I will use
// Array.reduce
// We gonna call couple, two values that goes together, like :
// User1 and 123456
// User2 and 456789
// ...
const ret = arr.reduce((tmp, x, xi) => {
// Add nothing for the first value of the couple
// We gonna ignore, User1, User2 and User3
if (xi % 2 === 0) return tmp;
return [
...tmp,
// Add a new value in the array
{
// The name is the first value of the couple
name: arr[xi - 1],
// The id is the second value of the couple
id: x,
},
];
}, []);
console.log(ret);
The for loop works on all versions of all computers and has the added advantage of being able to skip the index directly, something forEach can only do with a lot of extra code. Also forEach is slower than the for loop.
var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) { // here is the i+=2
arr2.push({
"name": arr1[i],
"user": arr1[i + 1] // here is the i+1
});
}
console.log(arr2)
Or terser array
var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) {
arr2.push({
[arr1[i]]: arr1[i + 1]
});
}
console.log(arr2)
A solution to your problem would be as follow :
var arr2 = [];
for (var i = 0; i < arr.length; i = i + 2) {
arr2.push({name : arr[i], id: arr[i + 1]})
}
Next time time try to show your trial code, you'll progress much more this way.

How to stop duplicate values in a loop?

I am using this code to read all the values from each object with the key "category":
const listChapter = datas.map((data) => console.log(data.category))
datas is an array of Objects, and there are 45 objects.
The problem is that when I console.log that, i have many duplicates values, you can see that below:
console.log results
I want to have one unique value of each category. How can I do that?
Filter duplicates from the data before you iterate through them.
var unique = datas.reduce(function(unique, data) {
return unique.indexOf(data.category) === -1 ? unique.concat(data.category) : unique;
}, []);
You also can do the trick with the Set:
let data = ['Alfa', 'Alfa', 'Beta', 'Gamma', 'Beta', 'Omega', 'Psi', 'Beta', 'Omega'];
let arr = [... new Set(data)];
// Or = Array.from(new Set(data));
console.log(arr);
Edit: I forgot that you have array of objects. In that case:
let data2 = [
{'category': 'Alfa'},
{'category': 'Alfa'},
{'category': 'Beta'}
]
let set = new Set();
data2.forEach((data) => {
set.add(data.category);
});
let arr2 = [... set];
console.log(arr2);
This is minor improvement of Tomek's answer. (I am not able comment yet.)
const arr = [
{'category': 'Alfa'},
{'category': 'Alfa'},
{'category': 'Beta'}
];
const unique = [...new Set(arr.map(item => item.category))];
This approach is faster, because of less iterations:
const listChapter = Object.keys(datas.reduce((ac, el) => {
ac[el.category] = true
return ac
}, {}))
arr is the whole array.
for(var i = 0; i < data.length; i++) {
if(arr[i] == data.category) {
remove item here;
}
}
Here's an alternative one-liner using filter() (just for fun):
console.log(datas.filter((data, i, a) =>
i === a.findIndex(data2 => data.category === data2.category)));

Pushing javascript object key value to javascript object key arrays

I'm having a stupid issue, probably due to my syntax. How can I dynamically push all keys from object arr[j] into object arr[i]?
var arr = [{key:["data1","data2"]},{key:"data"}];
var i = 0;
var j = 1;
for(var key in arr[i]){
arr[i][key].push(arr[j][key]);
// arr[i][key] is an array, arr[j[key;] is a string
}
Rather than brutally typing everything out (which works for me):
arr[i][key1].push(arr[j].key1);
arr[i][key2].push(arr[j].key2);
Arr[i] will then contain its previous information and object 2 information in the form of an array. Basically, I'm concatenating JavaScript objects. In the end, arr[i] should look like:
key1:[arr[i].key1Value,arr[j].key1Value]
key2:[arr[i].key2Value,arr[j].key2Value]
Thanks in advance!!
Relatively simple:
var arr = [{key:["data1","data2"]},{key:"data"}],
i = 0,
j = 1,
target = arr[i],
source = arr[j];
target.key.push(source.key);
If the source has multiple keys, try this instead:
var arr = [{key:["data1","data2"]},{key:"data", key1: "data1", key2: "data2"}],
i = 0,
j = 1,
target = arr[i],
source = arr[j];
for(var key in source){ // Loop over the keys in the source
target.key.push(source[key]); // And add them to the target's `key` array.
}
Result:
[
{ key: ["data1", "data2", "data", "data1", "data2"]},
{ key: "data", key1: "data1", key2: "data2"}
]
I am not 100% sure if I understand what you try to achieve but maybe this helps:
var arr = [{key:["data1","data2"]},{key:"data"}];
var target = [];
arr.forEach( function(value,index){
target['key' + index] = value;
});
Output:
target.key0 : { key: [ 'data1' 'data2' ]}
target.key1 : { key: [ 'data' ]}

Convert an array of object to array of string?

I'm having an array of object like this-
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
now i want output like this
var string_person = [{sparsh22XYZ},{ankur23},{Richa25ABXabc#xyz.co}];
is their any way to get output like this in javascript, jquery, Angular.js.
Any other web used language is approved.
Check out this jsfiddle. You'll see both Array.prototype.reduce and Array.prototype.map used, both with the same results.
This is classic reduce:
var people = person.reduce(function(agg, p) {
return agg.concat([p.name + p.age + p.address]);
}, []);
The above uses Array.prototype.reduce.
In other words, when you want all the properties of an object or array "reduced" into something, then the most semantic go-to option is probably Array.prototype.reduce in this case.
However, Array.prototype.map can also do the job quite cleanly:
var people = person.map(function(p) {
return p.name + p.age + p.address;
});
This is an argument, now, between readability/complexity vs. semantics.
To limit incidental complexity (in the form of readability), I might go for the map function, even though you could argue this is technically a paradigmatic reduction.
Try this, this method suitable for different object names, it will work good.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
var result = person.map(function(p){ return Object.keys(p).map(function(k){return p[k]}).join("");})
You can do it like this.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var test = person.map(function(one){
var properties = Object.getOwnPropertyNames(one);
return properties.map(function(prop){
return one[prop];
}).join('');
});
console.log(test);
I think it will help you.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var stringarray=[];
// $.each(person, function (i, d) {
// stringarray.push(d.name + d.age + d.address);
// });
//for(var i = 0; i < person.length; i++){
// stringarray.push(person[i].name + person[i].age + person[i].address);
//}
var stringarray = person.map(function(p) {
return p.name + p.age + p.address;
});
console.log(stringarray);
Result: ["saprsh22XYZ", "Ankur23ABC"]
Plz Try this one.
I assume you want a array of strings.
[{sparsh22XYZ},{ankur23ABC}]
is not such an array.
If you want
[ "sparsh22XYZ", "ankur23ABC" ]
you can simply go with
Plain old Javascript:
var string_person = [];
for (var i = 0; i < person.length; i++) {
string_person.push(person[i].name+person[i].age+person[i].address);
}
Underscore.js library
If all you need is a list of values of one of the object properties, it's easiest to go with underscore.js library.
var string_person = _.pluck(person, 'name');
http://underscorejs.org/#pluck
Call the below function on any array of Objects with any number of parameters, it will return you what you want.
function getStringArray(array){
var resultArray = [];
for (i = 0; i < array.length; i++) {
var result = "";
var keysArray = Object.keys(array[i]).sort()
for(j = 0; j < keysArray.length; j++){
result = result+array[i][keysArray[j]];
}
resultArray.push(result);
}
return resultArray;
}
var string_person = [];
for(var i = 0; i < person.length; i++){
string_person.push(person[i].name + person[i].age + person[i].address);
}
Updated:
Also You can use Underscore:
var string_person = _.map(person, function(p){return p.name + p.age + p.address;});
I guess you want to join all members of the object to a string. There are two ways to do this:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
var obj = person[index]; // save the object temporally
person[index] = ''; // place an empty string at the index of the object
// iterate through all members of the object using the "in"-operator
for (var member in obj) {
person[index] += obj[member]; // add the value of the member to the string
}
}
The problem with this technique is, I cannot guarantee that it will join the values of the members in the order you want. It should join them in the order in which the members were defined.
Anyway this solution works fine but only in your case:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
// place a string which contains the joined values of the members in the right order at the index of the object
person[index] = [
person[index].name,
person[index].age,
person[index].address
].join('');
}

Categories