I would like to get result like
arr=['A','B','C','D']
from the object like below.
var obj = {
obj1: 'A',
obj2: [ 'B', 'C', 'D' ] }
How to reach out to concatenate to array?
If someone has opinion, please let me know.
Thanks
You can get the values using Object.values() and to get them in one array you can use Array.prototype.flat():
var obj = {
obj1: 'A',
obj2: ['B', 'C', 'D']
}
var arr = Object.values(obj).flat()
console.log(arr)
You can make use of Object.values and spread it into a single array with Array.prototype.concat since Array.prototype.flat is not supported in older browsers
var obj = {
obj1: 'A',
obj2: ['B', 'C', 'D']
}
var vals = [].concat(...Object.values(obj))
console.log(vals)
Quick solution is to create an array of obj1 and concat the obj2.
const arr = [obj.obj1].concat(obj.obj2);
You can use reduce() followed by Object.values()
var obj = {
obj1: 'A',
obj2: [ 'B', 'C', 'D' ]
};
const res = Object.values(obj).reduce((acc, curr) => [...acc, ...curr], []);
console.log(res);
Related
anyway I can unpack an array into an object that each element of array as the key of object and value is 0? something like
const arr = ['a', 'b', 'c', 'd']
//I want to have
//const obj = {'a': 0, 'b': 0, 'c': 0}
Use Object.fromEntries combined with the array .map method:
const arr = ['a', 'b', 'c', 'd']
//I want to have:
//const obj = {'a': 0, 'b': 0, 'c': 0}
console.log(Object.fromEntries(arr.map(x => [x, 0])))
You could use Array.prototype.reduce() method to make your required object.
const arr = ['a', 'b', 'c', 'd'];
const ret = arr.reduce((prev, c) => {
const p = prev;
p[c] = 0;
return p;
}, {});
console.log(ret);
From an array of keys and an array of arrays, like this:
const keys = ['foo', 'bar'];
const vals = [
['a', 'A'],
['b', 'B']
];
How to get an array of objects like below ?
[
{'foo' : 'a', 'bar' : 'A'},
{'foo' : 'b', 'bar' : 'B'}
]
Maybe using lodash ?
You can use loash's _.zipObject() to create an object from an array of keys and values for each value array inside your 2d array using the _.map() method:
const keys = ['foo', 'bar']
const vals = [
['a', 'A'],
['b', 'B']
];
const res = _.map(vals, arr => _.zipObject(keys, arr));
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
If you prefer vanilla JS, then you could use Object.fromEntries() on a zipped array (created using .map()):
const keys = ['foo', 'bar']
const vals = [
['a', 'A'],
['b', 'B']
];
const res = vals.map(
arr => Object.fromEntries(arr.map((v, i) => [keys[i], v]))
);
console.log(res);
To be more generic, you can use Array.reduce() with index variable
const keys = ['foo', 'bar']
const values = [
['a', 'A'],
['b', 'B']
]
const mapped = values.map(val => val.reduce((acc, cur, i) => ({...acc, [keys[i]]: cur}),{}))
console.log(mapped)
With lodash/fp you can generate a function using _.flow(), that curries _.zipObject() with the keys, and the _.map() with the curried _.zipObject(), and then you can call it with vals to get the array of objects:
const fn = _.flow(_.zipObject, _.map);
const keys = ['foo', 'bar']
const vals = [
['a', 'A'],
['b', 'B']
];
const result = fn(keys)(vals);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
You can do it simply using reduce.
let keys = ['foo', 'bar'];
let values = [
['a', 'A'],
['b', 'B']
];
const res = values.reduce((a, [first, second]) => {
return [...a, {[keys[0]]: first, [keys[1]]: second}];
}, []);
console.log(res);
.as-console-wrapper{min-height: 100%!important; top:0}
let dataKeys = ['foo', 'bar'];
let dataValues = [
['a', 'A'],
['b', 'B']
];
let transformed = dataValues.reduce((result,item)=>{
result.push(
dataKeys.reduce((r,dk,index)=>{
let o = {};
o[dk]= item[index];
return {...r, ...o}
},{})
)
return result
},[]);
console.log(JSON.stringify(transformed,null,2));
I have and array of arrays aa = [['a'], ['b'], ['c']] and i have an array a = ['a', 'b', 'c']
I need to get the item in aa for each element in a i.e i want to list elements in a with their respective arrays in aa the result should be like
a: ['a'] b: ['b'] c: ['c']
I tried this code but it does return the first element i aa for each element in a
I wonder what's wrong here
const aa = [
['a'],
['b'],
['c']
]
const a = ['a', 'b', 'c']
let b = []
a.forEach((el) => {
b.push(
aa.filter((element) => {
return element.includes(el)
})
)
})
console.log(b)
Try this
const aa = [
['a'],
['b'],
['c']
];
const a = ['a', 'b', 'c'];
let b = {};
a.forEach( // loop "a"
aEl => b[aEl] = aa.filter( // filter "aa"
aaEl => aaEl.includes(aEl) // on array that includes the item from 'a'
).flat() // we need to flatten the resulting array before returning it
);
console.log(JSON.stringify(b)); // using stringify to make it readable
Since you want your output to be a key-value list (a: ['a']), variable b should be a map. Let's also rename b to out for readability.
out = {}
To get a better view of if our code is working, let's use some unique test data, and let's rename a to keys and aa to values.
const keys = ['A', 'B', 'C']
const values = [
['A', 'A2', 'a3'],
['B1', 'B', 'b3'],
['C1', 'C2', 'C']
]
For every key in keys, we want to set search for all arrays in values that contain the key. To set the search result to out we use brackets like so:
keys.forEach((key) => {
out[key] = values.filter(valueArr => valueArr.includes(key))
})
This outputs:
{
"A": [["A", "A2", "a3"]],
"B": [["B1", "B", "b3"]],
"C": [["C1", "C2", "C"]]
}
Now there are two arrays around each value. This is because values.filter can return multiple arrays. To combine these into a single array you can use the flat() function. The whole code looks like:
const keys = ['A', 'B', 'C']
const values = [
['A', 'A2', 'a3'],
['B1', 'B', 'b3'],
['C1', 'C2', 'C']
]
out = {}
keys.forEach((key) => {
out[key] = values.filter(valueArr => valueArr.includes(key)).flat()
})
console.log(out)
Hi I was wondering if I can get some help here I am stuck. I am trying to create a histogram function that takes an array like ['a', 'a', 'b', 'c', 'b', 'a'] and returns {a:3, b:2, c:1} using the reduce function to build the histogram function. But I am stuck on what the callback function should be.
Thank you for any responses.
You can reduce your array like this:
['a', 'a', 'b', 'c', 'b', 'a'].reduce(function(obj, value) {
obj[value] = obj[value] || 0;
obj[value]++;
return obj;
}, {});
If your environment supports Object.assign() and ES6 you can also do this:
['a', 'a', 'b', 'c', 'b', 'a']
.reduce((a, b) => Object.assign(a, {[b]: a[b] ? ++a[b] : 1}), {});
Try to iterate over the array and fill/increment the object's value accordingly,
var x = ['a', 'a', 'b', 'c', 'b', 'a'];
var y = {};
x.forEach(function(itm){
y[itm] = ++y[itm] || 1;
});
How can I create an object from two arrays without using loops in javascript.
example:
array1 = [1,2,3,4,5];
array2 = [A,B,C,D,E];
I want from below object
obj = {
'1': 'A',
'2': 'B',
'3': 'C',
'4': 'D',
'5': 'E',
}
Thanks in advance
var obj = {}
array1 = [1, 2, 3, 4, 5];
array2 = ['A', 'B', 'C', 'D', 'E'];
array1.forEach(function(value, index) {
obj[value] = array2[index];
});
console.log(obj);
Try to use $.each() to iterate over one of that array and construct the object as per your requirement,
var array1 = [1,2,3,4,5],array2 = ['A','B','C','D','E'];
var obj = {};
$.each(array2,function(i,val){
obj[array1[i]] = val;
});
DEMO
An ES6, array reduce solution.
const array1 = [1, 2, 3, 4, 5];
const array2 = ['A', 'B', 'C', 'D', 'E'];
const resultMap = array1.reduce(
(accumulator, value, index) => Object.assign(accumulator, {
[value]: array2[index],
}), {}
);
console.log(resultMap);
just for fun created something like this without using any iteration methods.
const array1 = [1,2,3,4,5];
const array2 = ['A','B','C','D','E'];
let combineKeyValueProxy = new Proxy({}, {
set: function(target, prop, value, receiver) {
target[array1[prop]] = value;
return true
}
});
const output = Object.assign(combineKeyValueProxy, array2);
console.log(output) // Proxy {1: "A", 2: "B", 3: "C", 4: "D", 5: "E"}