I have some data that comes like an array, i will show you it looks
Vm.table=[{
Name:"amina";
},
{
Prenom:"adfe";
},
{
Region:"rabat";
}];
To an object like
Vm.obj={
Name:"amina",
Prenom:"adfe",
Region:"rabat"
};
I need to set a code that may convert the table to this object, i put a lot of functions but is not working to me if someone can help.
You can use Object.assign() and spread operator
const table=[{Name:"amina"},{Prenom:"adfe"},{Region:"rabat"}];
const result = Object.assign({}, ...table);
console.log(result);
You can use reduce
Vm.obj = Vm.table.reduce((obj, col) => {
Object.keys(col).forEach(k => obj[k] = col[k])
return obj;
}, {});
Of course, if you have repeating keys, this will take the last key/val pair available.
Use Array.prototype.reduce and I am assuning objects have only single key, value pair.
let array =[{
Name:"amina"
},
{
Prenom:"adfe"
},
{
Region:"rabat"
}];
let obj = array.reduce((prev, curr) => {
const key = Object.keys(curr)[0];
prev[key] = curr[key];
return prev;
}, {});
console.log(obj);
Related
I have an array of objects like this:
const arr=[
{ name:"test",
class:3
},
{ name:"test2",
class:4
},
{ name:"test3",
class:5
},]
Now I have to convert it to a map like structure as shown below:
const map={
"name":["test","test2","test3"],
"class":[3,4,5]
}
I am clueless on how to make this kind of structure.Any leads will be appreciated.
If you have an arbitrary amount of keys you can use Object.entries()
to get all the key value pairs. Then just loop over all entries and add them to the final output.
const arr=[{name:"test",class:3},{name:"test2",class:4},{name:"test3",class:5}];
const map = arr.reduce((acc, obj) => {
for(const [key, value] of Object.entries(obj)) {
if(acc[key]) {
acc[key].push(value);
}else{
acc[key] = [value];
}
}
return acc;
}, {});
console.log(map);
Have a function that accepts the array and the property you're looking for, and return a new array of data using map for each property of your new object.
const arr=[{name:"test",class:3},{name:"test2",class:4},{name:"test3",class:5}];
function getData(arr, prop) {
return arr.map(obj => obj[prop]);
}
const map = {
name: getData(arr, 'name'),
class: getData(arr, 'class')
}
console.log(map);
It should be something like that
arr.reduce((res, obj) => {
Object.entries(obj).forEach(([k,v]) => {
if(!res[k]) res[k] = []
res[k].push(v)
})
return res
},{})
I have a javascript array as
arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}]
I want a new array as:
new_arr = [{"class":"a", "sub_class":"b", "category":"c", "sub_category":"d"}]
Is it possible to do this in Javascript without using a for loop to iterate through arr?
You can use Object.assign:
const array = [{
"class": "a"
}, {
"sub_class": "b"
}, {
"category": "c"
}, {
"sub_category": "d"
}]
const mergedObject = Object.assign({}, ...array);
// And put in an Array if that was intentional
const newArray = [mergedObject];
console.log(newArray);
I think that you want to merge objects. You could either use a spread operator or Object.assign. I don't see the point of having a single object inside an array. Considering your requirements you could do:
const merged = arr.reduce((list, curr) => {
return Object.assign({}, list, curr);
}, {});
const newArr = [merged];
You can try this.
var arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}];
var res=[];
var res1=[];
res=Object.assign(...arr);
res1.push(res);
console.log("Result: ",res1);
I have two object arrays. I want to merge with key with value
var a = [{"fit":["34","32","30","28"],"size":["x"]}]
var b = [{"size":["s","m","xl"],"fit":["36"]}]
Expected Output should be
Obj=[{"fit":["34","32","30","28","36"],"size":["x,"s","m","xl"]}]
My Code is
let arr3 = [];
b.forEach((itm, i) => {
arr3.push(Object.assign({}, itm, a[i]));
});
alert(JSON.stringify(arr3))
it gives [{"size":["x"],"fit":["34","32","30","28"]}] which wrong.
Use Array.reduce().
// Combine into single array (spread operator makes this nice)
const myArray = [...a, ...b];
// "reduce" values in array down to a single object
const reducedArray = myArray.reduce((acc, val) => {
return [{fit: [...acc.fit, ...val.fit], size: [...acc.size, ...val.size]}];
});
Edit: if you want the reducer to merge objects regardless of what keys and fields it has then you can do by iterating over the keys of the objects and merging them dynamically:
const reducedArray = myArray.reduce((acc, val) => {
const returnObject = {};
for (const eaKey in acc) {
returnObject[eaKey] = [...acc[eaKey], ...val[eaKey]];
}
return [returnObject];
});
If the fields of the objects aren't guaranteed keys then you will need to get even more dynamic in detecting the type of merge and how to do it, but it's possible and I will leave that as an exercise for you to figure out. :)
Note that if there are duplicate values in each of the "fit" and "size" arrays, they will not be deduplicated. You'd have to do that manually as a separate step either with extra logic in the reduce function or afterwards.
combine a and b in a single array then reduce it starting with an array having an object with empty fit and size arrays:
var a = [{ fit: ["34", "32", "30", "28"], size: ["x"] }];
var b = [{ size: ["s", "m", "xl"], fit: ["36"] }];
var obj = [...a, ...b].reduce(
(acc, curr) => {
Object.keys(curr).forEach(k => {
acc[0][k] = [...new Set([...(acc[0][k] || []), ...curr[k]])];
});
return acc;
},
[{}]
);
console.log(obj);
You can create a combine function that takes fit and size from any two objects and merges them.
Use it as a reducer to combine everything.
let combine = ({fit, size}, {fit: fit2, size: size2}) =>
({ fit: [...fit, ...fit2], size: [...size, ...size2] });
let result = [...a, ...b].reduce(combine);
Example:
var a = [{"fit":["34","32","30","28"],"size":["x"]}, {"fit": ["10", "11"], "size":["xxxxxxxxl"]}]
var b = [{"size":["s","m","xl"],"fit":["36"]}];
let combine = ({fit, size}, {fit: fit2, size: size2}) =>
({ fit: [...fit, ...fit2], size: [...size, ...size2] });
let result = [...a, ...b].reduce(combine);
console.log(result);
If you don't want to use the keys directly you could try
const arr3 = b.reduce((carry, current, index) => {
Object.keys(current)
.forEach(key => {
Object.assign(carry, { [key]: Array.prototype.concat.call(current[key], a[index][key])});
});
return carry;
}, {});
I have an array like this
let oldArray=[
{type:16,img:['1']},
{type:16,img:['2']},
{type:16,img:['3']},
{type:17,img:['4']}
]
if the type is the same, i want to concat the value.
The result I want is:
let newArray=[
{type:16,img:['1','2','3']},
{type:17,img:['4']}
]
I tried to used reduce function:
oldArray.reduce((acc,cur,idx,src)=>{
if(cur.type===a[idx+1].type){
cur.img.concat(a[idx+1].img);
acc.push(cur)
} else {
acc.push(a[idx+1])
}
return acc
},[])
It seems that there is an error
Can anyone help? Thanks.
Alternative to Bibberty's solution:flatMap is much clearer than reduce
let newArray = [...new Set(oldArray.map(e => e.type))]
.map(e => {
return {
type: e,
img: (oldArray.filter(i => i.type === e).map(x => x.img)).reduce((acc,cur,idx,src)=>{
let length=src.length
let tep=cur.concat(src[idx+1]);
src[idx+1]=tep
return src[idx=length-1]
},[])
}
});
console.log(newArray);
You can use reduce:
let oldArray = [{type: 16,img: ['1']},{type: 16,img: ['2']},{type: 16,img: ['3']},{type: 17,img: ['4']}];
let newArray = oldArray.reduce((acc, curr) => {
acc.some(({
type
}) => type == curr.type) ? acc.find(({
type
}) => type == curr.type).img.push(curr.img[0]) : acc.push(curr);
return acc;
}, []);
console.log(newArray);
We use a Set and then a map.
The Set is populate with the unique types by using a map to extract.
We wrap in [] to give us an array the we then re map to build our object back.
The map then rebuilds our objects and note the use of filter and map to get the img values from the original host array.
let oldArray=[
{type:16,img:['1']},
{type:16,img:['2']},
{type:16,img:['3']},
{type:17,img:['4']}
]
let newArray = [...new Set(oldArray.map(e => e.type))]
.map(e => {
return {
type: e,
img: oldArray.filter(i => i.type === e).flatMap(x => x.img)
}
});
console.log(newArray);
This solution is not a reduce but return result you are looking for is the same
let oldArray = [
{type:16,img:['1']},
{type:16,img:['2']},
{type:16,img:['3']},
{type:17,img:['4']}
];
const transitoryMap = new Map();
for (const item of oldArray) {
if (!transitoryMap.has(item.type)) {
transitoryMap.set(item.type, [item.img[0]])
} else {
const value = transitoryMap.get(item.type)
value.push(item.img[0])
transitoryMap.set(item.type, value)
}
}
const newArray = [];
for (const item of transitoryMap.keys()) {
newArray.push({type:item,img:transitoryMap.get(item)})
}
console.log(newArray)
Here is an example using reduce. I have added a tracker to keep track of type in the newArray.
let oldArray = [
{type:16,img:['1']},
{type:16,img:['2']},
{type:16,img:['3']},
{type:17,img:['4']}
];
oldArray.reduce((a,c)=>{
let index = a.tracker.indexOf(c.type);
if(index === -1) {
a.tracker.push(c.type);
a.newArray.push({...c, img:[...c.img]});
} else {
a.newArray[index].img.push(...c.img);
}
return a;
},{tracker:[],newArray:[]}).newArray;
You might want to consider breaking up the processing into separate simple steps, for example:
Create a flattened object with the appropriate data.
build a new array with the wanted structure.
This will not only keep your code simple, but will allow you to focus on what your code is actually doing instead of how it is doing the task.
var oldArray=[
{type:16,img:['1']},
{type:16,img:['2']},
{type:16,img:['3']},
{type:17,img:['4']}
]
flattenMyObject = (arr) =>
arr.reduce((accum, current) => {
!!accum[current.type] ? accum[current.type].push(...current.img) : accum[current.type] = current.img;
return accum;
}, {});
buildNewArray = (type) => {
return {type: type, img: flattenedObject[type] }
}
Object
.keys(flattenMyObject(oldArray))
.map(buildNewArray);
Please read fully. Do not mark it duplicate until you really find it. I have an array of objects like below.
const filterParams = [
{ 'waterfront_type[]': 'Cove' },
{ 'area[]': 'Applehead Island' },
{ 'waterfront_type[]': 'Channel' },
{ 'waterfront_type[]': 'Open Water' },
{ baths: '0 - 14' },
{ price: '0.00 - 9,876,100.00' }
];
I need to loop over this and add this to form data. I'm doing like below.
filterParams.map(param => {
return formData.append(param.key, param.value);
});
Expected: param.key is waterfront_type[] and param.value is Cove. so internally it should be formData.append('waterfront_type[]', 'Cove');
Getting: both undefined. formData.append(undefined, undefined);
You can use Object.entries(), and array destructuring to get the key, and the value.
Note: the default = [] handles the case of empty objects.
filterParams.map(param => {
const [[key, value] = []] = Object.entries(param);
return formData.append(key, value);
});
If you just need to call formData(key, value), and you don't care about the returned values (if any), use Array.forEach() instead of Array.map():
filterParams.forEach(param => {
const [[key, value] = []] = Object.entries(param);
formData.append(key, value);
});
param variable passed to .map function is a javascript object and you cannot access its keys by using just object.key. Instead do:
filterParams.map(param => {
var keys = Object.keys(param);
return formData.append(keys[0], param[keys[0]]);
});
Here, we are getting all the keys of the param object and get the first (0th index) as the key you require (assuming that your array have objects with one key).
So you want to put all dictionary entrySet into a FormData:
filterParams.forEach(param => {
Object.keys(param).forEach(function(key) {
let value = param[key];
formData.append(key, value);
});
});
It will produce the output of:
["waterfront_type%5B%5D=Cove",
"area%5B%5D=Applehead%20Island",
"waterfront_type%5B%5D=Channel",
"waterfront_type%5B%5D=Open%20Water",
"baths=0%20-%2014",
"price=0.00%20-%209%2C876%2C100.00"]
you can use javascript filters
filterParams = filterParams.filter(function(itm){
Object.keys(itm).forEach(function(key, value){
return formData.append(key, value);
})
})