How do you append an array of keys to object? - javascript

I have an array of strings and a params object like this. How do I create the params constant? Using either forEach, map, and or filter?
key = ['dog', 'car', 'cat'];
value = [ 3, 1, 2 ];
const params = {
item: {
[key]: value[0],
// more keys to be appended
}
}

Just looping through each value:
const key = ['dog', 'car', 'cat'];
const value = [ 3, 1, 2 ];
const item = {};
key.forEach((k, i) => { item[k] = value[i]; });
const parmas = {};
parmas.item = item;
console.log(parmas);

You can set an object's keys using the following syntax:
obj[key] = value
So in you case, you could do something like:
key = ['dog', 'car', 'cat'];
value = [ 3, 1, 2 ];
var params = {
item : {}
}
for (var i=0; i<key.length;i++){
params.item[key[i]] = value[i];
}

You could do it this way:
value.reduce((acc, val, index) => (acc[key[index]] = val, acc), {});
This produces:
{dog: 3, car: 1, cat: 2}

Related

how to create 2 arrays by running once on an array containing objects with the arrays matching the fields?

for example - lets say I have the array -
const array = [{name: "first", val: 1}, {name: "second", val: 2}]
I want to run once on that array and at the end of that run to have two arrays -
const arrayOne = ["first", "second"];
const arrayTwo = [1,2];
to get the first one is easy, but getting both at once?
I remember there was a way to do it but couldn't find it..
I'd appreciate any help!
Any looping logic will help
Array.reduce implementation will be like below
const array = [{ name: "first", val: 1 }, { name: "second", val: 2 }];
const [arrayOne, arrayTwo] = array.reduce((acc, curr) => {
const { name, val } = curr;
acc[0].push(name);
acc[1].push(val);
return acc;
}, [[], []]);
console.log(arrayOne, arrayTwo);
The function extractArrays is general-purpose and can be used in other cases as well.
function extractArrays(arr) {
const result = {};
for (obj of arr) {
for (key in obj) {
result[key] = (result[key] || []).concat([obj[key]]);
}
}
return result;
}
const array = [{name: "first", val: 1}, {name: "second", val: 2}];
const result = extractArrays(array);
const arrayOne = result.name;
const arrayTwo = result.val;
console.log(`arrayOne=${arrayOne}`);
console.log(`arrayTwo=${arrayTwo}`);
You can use Array.reduce to achieve this:
const array = [{name: "first", val: 1}, {name: "second", val: 2}]
const result = array.reduce((res, item) => {
res[0].push(item.name)
res[1].push(item.val)
return res
}, [[], []])
console.log(result)
thanks everyone!
but I think that the easiest, most readable code would be something like -
const itemArray = [], valArray = [];
data.map(({name, val})=> {
if(name) nameArray.push(name);
if(val) valArray.push(val);
})
because basically in 4 lines of code it's finished
thanks again everyone!
const array = [{name: "first", val: 1}, {name: "second", val: 2}]
const keys = [];
const values = [];
array.forEach(item=>{
keys.push(item.name);
values.push(item.val);
})
console.log(keys, values)
Use the Array.map function:
const array = [ { name: 'first', val: 1 }, { name: 'second', val: 2 } ]
let names = array.map(item => item.name)
let vals = array.map(item => item.val)
console.log(names)
console.log(vals)
The map function calls a callback function you provide on each element and constructs a new array from the results of that function.
If you are not familiar with arrow functions like:
item => item.name
... it is a short form for:
function (item) {
return item.name
}
You could even do it in one line:
let [ names, vals ] = [ array.map(item => item.name), array.map(item => item.val) ]

How can I filter 2 object arrays in React?

const obj1 = [{'food': ['apple'], 'drink': ['wine', 'juice']}];
const obj2 = [{id: 1, 'food': ['apple'], dummy: 'test', 'drink':['wine', 'juice']},
{id: 2, 'food': 'banana', dummy: 'test', 'drink':['juice']},
{id: 3, 'food': ['apple', 'banana'], dummy: 'test'},'drink':['juice']}
];
//and result should be like this
const result = [{id:1, 'food': ['apple'], 'drink': ['wine', 'juice']}];
if there's two object arrays, how can I filter obj1 on obj2?
What I'm going to do is
if obj1 has same value with obj2, leave obj2's objects that contains same
value with obj1.
set the state with those remained objects.
this is how I tried.
the problem of this logic is
returned value contains only filtered value.
ex) {food:['banana]}
but It has to return all object that contain 'banana', not only 'banana'.
(so that I can set State with filtered result)
//key arg is recived key from outside. (it should be 'food' or 'drink')
const showFilteredRes = (obj1, key) => {
let filteredRes = {};
obj2.forEach((obj2) => {
for (let filters in obj1) {
for (let infos in obj2) {
if (filters === infos) {
filteredRes[infos] = obj2[key];
console.log(filteredRes);
}
}
}
});
};
how can I develop this code?
I edited my example because my explanation was too poor.
const obj1 = [{
'food': ['banana'],
'drink': ['wine', 'juice']
}];
const obj2 = [{
id: 1,
'food': ['apple', 'custard'],
dummy: 'test',
'drink': ['wine', 'juice']
},
{
id: 2,
'food': ['banana'],
dummy: 'test',
'drink': ['juice']
},
{
id: 3,
'food': ['apple', 'banana'],
dummy: 'test',
'drink': ['juice', 'wine']
}
];
const showFilteredRes = (filtered, key) => {
let result = [];
filtered.forEach((filteredObj) => {
obj2.forEach((obj) => {
if (JSON.stringify(obj[key]) == JSON.stringify(filteredObj[key])) {
result.push(obj);
}
})
})
console.log(result);
};
showFilteredRes(obj1, "food");
Looping though the first Object and acquire the desired object using the deep compare arrays with same key.
Make use of some() :
const showFilteredRes = (filtered, key) => {
let filteredRes = {};
obj2.forEach(entry => {
if(entry[key].some(item => obj1[key].includes(item)))
{
console.log(filteredRes);
}
}

How to keep the type of each element in an array

I have an array which I want to keep the type of each element of this array
const arr = ['123', '456', 789];
// 123 and 256 are string, 789 a number
I would like this result:
const arr2 = ['1', '2', '3', '4', '5', '6', 7, 8, 9];
Maybe a simple array reduce will suit you ?
const arr = ['123', '456', 789];
const arr2 = arr.reduce((a,c)=>
{
if (Number.isInteger(c)) [ ...c.toString(10)].forEach(n=>a.push(Number(n)))
else a.push(...c)
return a
},[])
document.write ( JSON.stringify( arr2 ))
const arr = ['123', '456', 789];
const arr2 = arr
.map(itemToParse => {
const isString = typeof itemToParse === 'string';
const stringItemToParse = String(itemToParse);
const stringChunks = stringItemToParse.split('');
return stringChunks.map(chunk =>
isString ?
chunk :
parseInt(chunk))
})
.flat();
console.log(arr2);
const arr = ["123", "456", 786];
const newArr = [];
arr.forEach(elem => {
if (typeof elem == 'number') {
elem.toString().split('').forEach(ele => {
newArr.push(parseInt(ele));
})
} else {
elem.split('').forEach(ele => {
newArr.push(ele);
})
}
})
console.log(newArr) // ["1", "2", "3", "4", "5", "6", 7, 8, 6]
You can do it like this:
var arr = ['123', '456', 789];
var result = arr.flatMap((val=> Number.isFinite(val) ? [...val.toString()].map(k=>parseInt(k)) : [...val.toString()]));
console.log(result);
This will do the trick. I hope it helps. Thanks!
simply you can do it by 'reduce' method of array. btw, you can do it the same way with a map method.
when you iterate array of items, you can check it's type.
i converted every incoming value in string, because this is way to get every single symbol for the new results array.
then according it's type i create new array using rest operator and returns it with accumulator in the loop.
const arr = ["123", "456", 789]; // 123 and 256 are string, 789 a number
const arr2 = arr.reduce((acc, rec) => {
let data = rec + "";
let newArr = data.split("");
if (typeof rec === "string") {
newArr = newArr.map((it) => it);
return [...acc, ...newArr];
}
let num = newArr.map((it) => +it);
return [...acc, ...num];
}, []);
console.log(arr2);
const arr = ['123', '456', 789];
result = [];
function convertType (type,value){
switch(type){
case 'string':
return String(value);
break;
case 'number':
return Number(value);
break;
}
}
for(i=0;i<arr.length;i++){
var type = typeof(arr[i]);
var split = (arr[i] + '').split('').map((i) => { return Number(i); })
for(item of split){
var converted = convertType(type,item);
result.push(converted)
}
}
console.log(result);

javascript delete elements from array of objects that are not present in another array of objects

I have 2 arrays with different objects, but I need some kind of map function to map the 2 arrays to the newArray. The newArray has the same object type of arr1.
let arr = [{Id: 1, Name:'test'}, {Id: 2, Name:'test2'}]
let secondarr = [{value:'test'}, {value:'test3'}]
const newArray = [{Id: 1, Name: 'test'}, {Id: null, value: 'test3'}];
arr.forEach(element => {
let exists = false;
secondarr.forEach(i => {
if(i.value === element.Name) {
exists = true;
}
});
if(exists) {
secondarr = secondarr.filter(l => l.value !== element.Name);
}
if(!exists) {
arr = arr.filter(l => l.Name !== element.Name);
}
});
secondarr.forEach(element => {
const newObj = {Id: null, Name: element.value};
arr.push(newObj);
});
You can use map to walk arr2 and use find to get the matching element.
Try it online!
const arr1 = [{Id: 1, Name:'test'}, {Id: 2, Name:'test2'}]
const arr2 = [{value:'test'}, {value:'test3'}]
const newArray = arr2.map(x => {
// we search for the matching element.
const item = arr1.find(obj => obj.Name === x.value)
// if item exists get item, else create a new one
return item ? item : { Id: null, Name: x.value }
});
console.log(JSON.stringify(newArray))
output
[{"Id":1,"Name":"test"},{"Id":null,"Name":"test3"}]

Making object from array with similar keys

I have an array like this:
var array = ['test1', 'test2', 'test3', 'test4']
I would like to make a new object from this array, and they should have the same keys. Desired outcome should be like this:
var objectFromArray = [
{ responsibilityName: "test1" },
{ responsibilityName: "test2" },
{ responsibilityName: "test3" },
{ responsibilityName: "test4"}
]
How is this possible in js?
Adjusted to your comment: you can use reduce and map to flatten the arrays within the array of objects.
[Edit based on your comment]
const arr = [
{ responsabilityName: ['test1', 'test2', 'test3', 'test4'],
somethingElse: [1, 2, 3, 4] } ];
const arrMapped = arr
.reduce( (mappedArr, obj) =>
Object.keys(obj)
.map( key => obj[key].map( prop => ({ [key]: prop }) ) )
.reduce( (p, n) => p.concat(n), [] ),
[] );
console.log(arrMapped);
Iterate over the array, create objects in the other one. As simple as that.
var array = ['test1', 'test2', 'test3', 'test4']
var objectFromArray = []
array.forEach((v)=>{objectFromArray.push({"responsibilityname":v})})
use array.map and assign the value to the object
DEMO
var array = ['test1', 'test2', 'test3', 'test4'];
var result = array.map(function(el) {
var obj = {};
obj['responsibilityname'] = el;
return obj;
})
console.log(array);
console.log(result);
Loop over the array and return a new object using map or forEach etc.
var array = ['test1', 'test2', 'test3', 'test4']
var arr = array.map(value => {
return {responsibilityName: value};
})
console.log(arr);

Categories