Javascript convert array of objects to an array with only specific keys with ES6 - javascript

I have the following array
const array = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
What i want is to get
const finalarr = [1,3]
That is get an array of values with key value
So i have tried
const finalarr = arr.map(obj=>obj.value)
The above returns [1, undefined, 3];
I have also tried
const finalarr = arr.map(obj => {
if (obj.value) {
return obj.value;
}
})
but i still get [1, undefined,3]
How can i adjust this to only return the values of objects with a key value to eliminate the undefined key?

Use the function reduce because the function map returns an array with the same length of the source array.
const finalarr = arr.reduce((a, {value}) => {
if (value) a.push(value);
return a;
}, []);
Important: your approach is skipping the objects with values equal to zero 0.
Example
const arr = [{name:'one', value:1},{name:'two'},{name:'three', value:3}];
const finalarr = arr.reduce((a, {value}) => {
if (value) a.push(value);
return a;
}, []);
console.log(finalarr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

The Array .map method will return another array with the exact same size of the original array.
If you want a result with different size, you cannot do it with pure .map only.
What you can do is to first .filter out objects without .value property:
const array = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
const result = array
.filter(obj => typeof obj.value !== 'undefined')
.map(obj => obj.value);
console.log(result);
Otherwise, you can also use .reduce:
const array = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
const result = array.reduce((arr, obj) => {
if (typeof obj.value !== 'undefined')
arr.push(obj.value);
return arr;
}, []);
console.log(result);

You can use reduce
const array = [{name:'one;', value:1},{name:'two'},{name:'three', value:3}]
let final = array.reduce((op,{value})=>{
if(typeof value !== 'undefined'){
op.push(value)
}
return op
},[])
console.log(final)
map used to map complete array back with changed values it doesn't skip value you can use map and filter for you purpose
const arr = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
const finalarr = arr.filter(({value})=>typeof value !== 'undefined').map(({value})=> value)
console.log(finalarr)

Related

Find an Item in an array and add a value

I have two arrays , I want to find the item in Arr1 with Arr2 Keys and map the value of arr2 to arr1 if not found value should be 0.
const Arr1=['A','B','C']
const Arr2=[{key:'a',val:100},{key:'c',val:100}]
Expected Result:
const Arr3=[{key:'a',val:100},{key:'b',val:0},{key:'c',val:100}]
You could use map and find like this:
const Arr1=['A','B','C']
const Arr2=[{key:'a',val:100},{key:'c',val:100}]
const Arr3 = Arr1.map(c => {
const exists = Arr2.find(b => b.key === c.toLowerCase());
return exists || { key: c.toLowerCase(), val: 0 };
})
console.log(Arr3)
Or using reduce like this:
const Arr1=['A','B','C']
const Arr2=[{key:'a',val:100},{key:'c',val:100}]
const Arr3 = Arr1.reduce((r, a) => {
const exists = Arr2.find(b => b.key === a.toLowerCase());
const item = exists || { key: a.toLowerCase(), val: 0 }
return r.concat(item)
},[])
console.log(Arr3)
In context to you previous question you can still return a value if you want and convert keys to lowercase before compare.
const Arr1=['a','b','c']
var Arr2=[{key:'a',val:100},{key:'c',val:100}]
Arr2.map(val => {
if(Arr1.indexOf(val.key) >= 0 )
val.val = val
else
val = 0
})
Read on Array. methods.
const Arr1= [{key:'a',val:100},{key:'c',val:120}]
let obj = Arr1.find(o => o.key === 'a');
console.log(obj); // your object

How to use split on a string and then convert it to object in Javascript

I have an array:
let arr = ["a=1", "b=22", "c=11"];
And I want to split the string inside array so it becomes an object later, which will look like:
{a: 1, b: 22, c: 11}
Can I somehow do that
You could split the string an map new objects. Later assign all objects to a single object.
var array = ["a=1", "b=22", "c=11"],
object = Object.assign(
...array.map(s => ((k, v) => ({ [k]: +v }))(...s.split('=')))
);
console.log(object);
you can use array.forEach, so you wont be creating an array instead you will iterate through the array, and you can take each item and split so it will create an array
like item = ["a", "1"], you can assign the key as a to the object which is the first index and value is second index,The value is string so you can convert to number and return it.
let arr = ["a=1", "b=22", "c=11"];
var obj = {}
arr.forEach(o => {
var item = o.split("=");
return obj[item[0]] = Number(item[1])
})
console.log("required obj", obj)
You can use array#map with Object.assign() to create your object. string#split each word on = and generate the object.
let arr = ["a=1", "b=22", "c=11"],
result = Object.assign(...arr.map(word => {
let [key,value] = word.split('=');
return {[key] : +value};
}));
console.log(result);
You can also use array#reduce.
let arr = ["a=1", "b=22", "c=11"],
result = arr.reduce((r,word) => {
let [key,value] = word.split('=');
r[key] = +value;
return r;
}, {});
console.log(result);
Here, try this
let arr = ["a=1", "b=22", "c=11"];
const obj = {}
arr.forEach(i => {
const splitted = i.split('=')
obj[splitted[0]] = splitted[1]
} )
console.log(obj)

Javascript converting 2 string arrays to map

I have two string arrays keys and values:
let keys = [a,b,c,d]
let values = [1,2,3,4]
How to convert them into a map?
Expected output would be:
{a: "1", b: "2", c: "3", d: "4"}
you can use Map in ES6
var myMap = new Map();
// setting the values
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');
your answer :
for (let i = 0; i < keys.length; i++) {
myMap.set(keys[i], values[i]);
}
Firstly create an object. Then loop through your array and add the keys and values to the object.
let keys = ['a','b','c','d'];
let values = [1,2,3,4];
let obj = {};
keys.forEach((key, index) => {
obj[key] = values[index]
});
console.log(obj);
You can use array reduce on any of the array and use index to retrieve value from another array
let keys = ['a', 'b', 'c', 'd'];
let values = [1, 2, 3, 4];
let k = keys.reduce((acc, curr, index) => {
acc[curr] = values[index]
return acc;
}, {});
console.log(k)
First of all, you need to declare your string arrays properly.
let keys = ['a', 'b', 'c', 'd'];
let values = ['1', '2', '3', '4'];
var zip = (target, ...arr) => {
if (target == null) throw Error('Target is undefined');
if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
if (Array.isArray(target)) {
arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
} else if (typeof target === 'object') {
arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
} else {
throw Error('Unsupported target type');
}
return target;
}
var zipObj = (...arr) => zip.call(null, {}, ...arr);
var zipArr = (...arr) => zip.call(null, [], ...arr);
//console.log(zip({}, keys, values));
console.log(zipObj(keys, values)); // Zip object
//console.log(zip([], keys, values));
console.log(zipArr(keys, values)); // Zip array
.as-console-wrapper { top: 0; max-height: 100% !important; }
When using lodash this is a one-liner:
_.zipObject(keys,values)
This should do the trick:
let keys = ['a','b','c','d']
let values = [1,2,3,4]
let mapped = keys.reduce((accumulator, current, index) => {
accumulator[current] = values[index];
return accumulator;
}, {});
console.log(mapped)
// Result should be:
{a: 1, b: 2, c: 3, d: 4}
Reduce is a powerful method that can be used for all sorts of tasks.
Here we're "reducing" the given values of keys into an object where keys are the key and values are the correlating values.
The first parameter in reduce is a callback function that you need to pass along at minimum accumulator and current variables (can have different names); the other parameters are index and array which represent the current index of the iteration and the original array that is being iterated.
The second parameter is the initial value of the accumulator; by default it will be the first current value but in our case we set it to {} so we can treat it as an object.
I hope this helps!

input array as a param?

this is my code:
return s => counts.get(s) || 0;
// Sample call
I want this function to input 2 array's and on output an single array for example I call a function.
Example:
f(a,b)=array result with a and b two array
You could reduce the counts and map the count of given values. Then you need to udjust undefined values.
function fn(values, counts) {
return values
.map(
Map.prototype.get,
counts.reduce((map, s) => map.set(s, (map.get(s) || 0) + 1), new Map)
)
.map(v => v || 0);
}
console.log(fn(["wer", "tyu", "uio"], ["wer", "wer", "tyu", "oio", "tyu"]));
This is how you combine two arrays into one, Using the built in Array.prototype.concat
Solution
function combineArrays (a, b) {
return a.concat(b);
}
const array1 = [1,2,3];
const array2 = [4,5,6];
console.log(combineArrays(array1, array2));
However, your code example doesn't seem to match what you're asking. Perhaps you want to combine all counts from both arrays into a single value?
function addArrays(a, b) {
return a.concat(b).reduce((a, b) => a + b);
}
const array1 = [1,2,3];
const array2 = [4,5,6];
console.log(addArrays(array1, array2));
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

How to Convert an array into Object using javascript without using Object.assign

I had an array
[{0:{title:"test1"}},{1:{message1:"message1"}},{2:{message2:"message2"}}]
I want to get an Object in below format
{title:"test1",message1:"message1",message2:"message2"}
I am trying with below code but no luck
var rv = {};
for (var i = 0; i < messageArray.length; ++i)
if (messageArray[i] !== undefined) rv[i] = messageArray[i];`
It results me
{0: {title:"test1"}, 1: {message1:"message1"},2: {message2:"message2"}}
You should make your array flat
const rv = [];
for (var i = 0; i < messageArray.length; ++i) {
if (messageArray[i] !== undefined)
rv.push(messageArray[i]);
}
Then can use Array.reduce, it should look like
rv.reduce((result, element) => {
Object.keys(element).forEach((key) => {
result[key] = element[key];
});
return result;
}, {});
You can use reduce to summarize the data and Object.assign() to merge new properties into an object.
let arr = [{0:{title:"test1"}},{1:{message1:"message1"}},{2:{message2:"message2"}}];
let result = arr.reduce((c, v, i) => Object.assign(c, v[i]),{});
console.log(result);
If the key on your objects are not on sequence, you can use Object.values() to get the values.
let arr = [{0:{title:"test1"}},{1:{message1:"message1"}},{2:{message2:"message2"}}];
let result = arr.reduce((c, v, i) => Object.assign(c, Object.values(v)[0]), {});
console.log(result);
You can use .map() and .reduce():
let data = [
{0:{title:"test1"}},
{1:{message1:"message1"}},
{2:{message2:"message2"}}
];
let result = data.map((c, i) => c[i])
.reduce((a, c) => Object.assign(a, c), {});
console.log(result);
Docs:
Array.prototype.map()
Array.prototype.reduce()
You can combine the items by spreading into Object.assign(). Then get the internal values via Object.values(), and merge them again by spreading into Object.assign():
const data = [{0:{title:"test1"}},{1:{message1:"message1"}},{2:{message2:"message2"}}];
const result = Object.assign(...Object.values(Object.assign({}, ...data)));
console.log(result);
You can iterate over each property, and use Object.assign to extend the current object with each property.
var object = {};
var input = [{0:{title:"test1"}},{1:{message1:"message1"}},{2:{message2:"message2"}}];
for (var i = 0; i < input.length; i++) {
object = Object.assign(input[i][i], object);
}
console.log(object);
/*
{
"message2": "message2",
"message1": "message1",
"title": "test1"
}
*/
The following code should give desired results without Object.assign :
//Using map() and reduce()
var arr = [{0:{title:"test1"}},{1:{message1:"message1"}},{2:{message2:"message2"}}];
var result = arr.map(function(item,i){
return item[i];
})
.reduce(function(acc,item){
return {...acc,...item}
},{})
console.log(result); // {title: "test1", message1: "message1", message2: "message2"}
Hope this helps!

Resources