Please help to combine object keys values from json arrays by key.
const input=[{
"Date":"04/10/2019",
"Time":"15:35",
"Title":"Flight -\u00a0Group C",
"Description":"Arrival 19:40"
},
{
"Date":"04/10/2019",
"Time":"Evening",
"Title":"Welcome drinks",
"Description":"In the bar at\u00a0"
},
{
"Date":"05/10/2019",
"Time":"Morning",
"Title":"Breakfast",
"Description":"At leisure"
},
{
"Date":"05/10/2019",
"Time":"10:00",
"Title":"Something Else",
"Description":"At leisure"
}];
console.log(
Object.values(input.reduce((a, { Date }) => {
if (!a[Date]) a[Date] = { Date, activities: [] };
a[Date].activities.push();
return a;
}, {}))
);
I need a combined object keys values in javascript in the following way:
[
{
"date":"04/10/2019",
"activities":[
{
"Time":"15:35",
"Title":"Flight -\u00a0Group C",
"Description":"Arrival 19:40"
},
{
"Time":"Evening",
"Title":"Welcome drinks",
"Description":"In the bar at\u00a0"
}
]
},
{
"date":"05/10/2019",
"activities":[
{
"Time":"Morning",
"Title":"Breakfast",
"Description":"At leisure"
}
]
}
]
I am trying to get the result with my code but 'activities' are null...
I would highly appreciate your help.
Thank you in advance
If you are using parameter destructuring you could use ... rest param to get other properties after you take out the date.
const input=[{"Date":"04/10/2019","Time":"15:35","Title":"Flight - Group C","Description":"Arrival 19:40"},{"Date":"04/10/2019","Time":"Evening","Title":"Welcome drinks","Description":"In the bar at "},{"Date":"05/10/2019","Time":"Morning","Title":"Breakfast","Description":"At leisure"},{"Date":"05/10/2019","Time":"10:00","Title":"Something Else","Description":"At leisure"}]
const object = input.reduce((r, { Date: date, ...rest}) => {
if(!r[date]) r[date] = {date, activities: [rest]}
else r[date].activities.push(rest)
return r
}, {})
const result = Object.values(object)
console.log(result)
Related
Say I have an array of objects as follows:
data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
]
and another array as follows:
myNumberArray = [1,2,3,4]
They might be much larger, but the number of elements in both arrays will always be the same. I want to modify each element of data by adding a number attribute, assigning it the value from the corresponding element of myNumberArray.
When done, data will look as follows:
data = [
{
"number":1,
"id":34
},
{
"number":2,
"id":35
},
{
"number":3,
"id":36
},
{
"number":4,
"id":37
}
]
How can I do this?
myNumberArray = [1,2,3,4]
data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
]
data.forEach((elem, index)=>{
data[index]["number"]=myNumberArray[index];
})
console.log(data);
This should solve your problem.
Explanation:
I used forEach to iterate over the data array, forEach accepts two parameters, the current value at an index, and the value.
Since, yours is a one-to-one mapping, we are using the current index to access the value at the same index in myNumberArray and assigning that new value in data for number key.
Try the following solution:
let myNumberArray = [1,2,3,4];
let data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
];
const updatedArray = data.map((item,index)=> {
return {
...item,
"number":myNumberArray[index]
}
});
console.log(updatedArray);
let myNumberArray = [1,2,3,4]
let data = [
{
"id":34
},
{
"id":35
},
{
"id":36
},
{
"id":37
}
]
data = data.map( (x, i) => ({ number: myNumberArray[i], id: x.id}) )
console.log(data)
for (let i in myNumberArray) {
Object.assign(data[i], {
number: myNumberArray[i]
})
}
I am having difficulties formatting some data. Currently, I receive data in the following structure.
[
{
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
}
]
I essentially need to modify this or even create a new object, that takes the following structure.
[
{
id: 1, //q1
answers: [
{
answer: '5',
},
],
},
{
id: 2, //q2
answers: [
{
answer: '13',
},
{
answer: '12',
},
],
},
{
id: 3, //q3
answers: [
{
answer: 'test',
},
],
},
];
So the id in the above would be obtained by remove the q and getting the number in the first data object. It would then have an answers array that would have an object for each answer.
I have been attempting this but have gotten lost. I don't know if I should use loops, mapping, filters etc. To be honest, the furthest I have got so far is obtaining the keys
var modified = data.map(function(item) {
return Object.keys(item)
})
I have created a JSFiddle where I have been attempting to do this.
Is there any way I can achieve the data I am after?
Many thanks
Please use map function.
const data = {
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
};
const result = Object.keys(data).map(key => {
let item = {id: key.substring(1), answers: []};
if(typeof data[key] === "string")
item.answers.push({answer: data[key]});
else
item.answers = data[key].map(val => ({answer: val}));
return item;
});
console.log(result)
const inputData = [
{
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
}
]
function answerMapper(objVal, id){
return Array.isArray(objVal)
?
{ id, answers: objVal.map(answer => ({ answer }))}
:
{ id, answers: [{answer: objVal }] }
}
function formatObject(obj){
return Object.keys(obj).map((k, i) => answerMapper(obj[k], i+1));
}
const result = inputData.map(obj => formatObject(obj));
// remove flatMap if your inputData has more than one entry
console.log(result.flatMap(x => x));
map over the first element of the data with Object.entries, grab the key and value, create a new answers array and return a new object.
const data = [{
"q1": "5",
"q2": [
"13",
"12",
],
"q3": "test",
}];
const out = Object.entries(data[0]).map(obj => {
const [ key, value ] = obj;
const id = Number(key[1]);
// If the the value is an array
// return a new array of mapped data
// Otherwise return an array containing
// one object
const answers = Array.isArray(value)
? value.map(el => ({ answer: el }))
: [{ answer: value }];
// Return the new object
return { id, answers };
});
console.log(out);
lets create a pure function which accepts the object in the array like so
const processObject = obj => Object.keys(obj).map(id => {
const answer = obj[id];
const answers = Array.isArray(answer) ? answer : [answer]
const answerObjectArray = answers.map(ans => ({
answer: ans
}));
return {
id: +id.substring(1),
answers: answerObjectArray
}
});
const dataArray = [{
"q1": "5",
"q2": [
"13",
"12",
],
"q3": "test",
}];
const output = processObject(dataArray[0]);
console.log(output);
I have an array like this.
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
I want to change it to like this
let me explain it a little. I want to assign the abbreviation directly to the name and the iterate through that array
let outout = [
{
"ISB":"ISLAMABAD"
},
{
"RAW":"ISLAMABAD"
},
{
"SWB":"SWABI"
},
{
"AQ":"AQEEL"
},
]
that is what I tried
let k = arr.map((item) => {
return item.ABB = item.name
})
console.log(k)
and here is the output
[ 'ISLAMABAD', 'PINDI', 'SWABI', 'AQEEL' ]
Here you go, use array map, simples
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
let outout = arr.map(({ABBRIVATION, name}) => ({[ABBRIVATION]: name}));
console.log(outout);
Nothing more than a simple Array.prototype.map() needed.
let arr = [
{
ABBRIVATION: "ISB",
name: "ISLAMABAD",
},
{
ABBRIVATION: "RAW",
name: "PINDI",
},
{
ABBRIVATION: "SWB",
name: "SWABI",
},
{
ABBRIVATION: "AQ",
name: "AQEEL",
},
];
const result = arr.map(e => ({ [e.ABBRIVATION]: e.name }));
console.log(result);
map over the array of objects (map returns a new array) and assign the name to a new key defined by the abbreviation.
You code works the way it does because item.ABB is undefined, but you're also assigning item.name to it which does get returned, so you just get an array of names returned.
const arr=[{ABBRIVATION:"ISB",name:"ISLAMABAD"},{ABBRIVATION:"RAW",name:"PINDI"},{ABBRIVATION:"SWB",name:"SWABI"},{ABBRIVATION:"AQ",name:"AQEEL"}];
const out = arr.map(obj => {
return { [obj.ABBRIVATION]: obj.name };
});
console.log(out);
Hi I have seen people answer, but most of them use the map function, I provide some other solutions, hoping to expand the thinking
Use forEach function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
datas.forEach((obj, i, arr) => {
const{'ABBRIVATION':k, 'name':v} = obj;
arr[i] = {[k]:v};
});
console.log(datas);
Use flatMap function
const datas = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
}
];
const result = datas.flatMap(obj => {
const {'ABBRIVATION':k, 'name':v} = obj;
return {[k]:v};
});
console.log(result);
this is how you suppose to do it.
arr.reduce((d, c)=>([...d, {[c.ABBRIVATION]: c.name}]),[])
let arr = [
{
"ABBRIVATION":"ISB",
"name":"ISLAMABAD",
},
{
"ABBRIVATION":"RAW",
"name":"PINDI",
},
{
"ABBRIVATION":"SWB",
"name":"SWABI",
},
{
"ABBRIVATION":"AQ",
"name":"AQEEL",
},
]
console.log(arr.reduce((data, current)=>([...data, {[current.ABBRIVATION]: current.name}]),[]))
I need to reformat my object of dates and I have an array of dates in such format:
Object {
"FREETIME": "2021-04-19 11:30:00",
},
Object {
"FREETIME": "2021-04-19 12:00:00",
},
Object {
"FREETIME": "2021-04-20 12:30:00",
},
Object {
"FREETIME": "2021-04-21 12:50:00",
},
and I would want to render them in section list like this:
const DATA = [
{
title: "2021-04-19",
data: ["11:30:00", "12:00:00"]
},
{
title: "2021-04-20",
data: ["12:30:00"]
},
{
title: "2021-04-21",
data: ["12:50:00"]
},
];
so what I do is first split the array of FREETIME by days and times:
const dates = data.map((item) => item.FREETIME.split(" "));
then I get unique days for section header of SectionList:
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
const days = dates.map((item) => item[0]).filter(onlyUnique);
and then I try to construct new object DATA with days and corresponding times but fail at mapping the times correctly:
const DATA = days.map((dayHeader) => ({
title: dayHeader,
data: //don't know how to map it properly here
}));
What am I doing it wrong or is there another approach to this?
Below is one method of doing the job with Array.prototype.reduce
const arrayOfObjectDates = [
{
"FREETIME": "2021-04-19 11:30:00",
},
{
"FREETIME": "2021-04-19 12:00:00",
},
{
"FREETIME": "2021-04-20 12:30:00",
},
{
"FREETIME": "2021-04-21 12:50:00",
}
];
const DATA = arrayOfObjectDates.reduce((op, { FREETIME }) => {
var [date, time] = FREETIME.split(" "), { result, index } = op;
if (index.hasOwnProperty(date)) {
result[index[date]].data.push(time);
} else {
index[date] = result.length;
result.push({ title: date, data: [time] });
}
return op;
}, { result: [], index: {} }).result;
console.log(DATA)
I am trying to filter a sub array of a parent array and my results are coming back empty. I am trying to find matches to the color_family.
My array looks like:
const arr =[
{
"id": 123,
"acf": {
"product_colors": [
{
"color_family": "grey"
},
{
"color_family": "taupe"
}
]
}
},
{
"id": 456,
"acf": {
"product_colors": [
{
"color_family": "red"
},
{
"color_family": "taupe"
}
]
}
}
]
What I am filtering on is
const findColors = ["grey", "taupe"]
What I have tried with no luck is
const res = arr.filter(
x => x.acf.product_colors.find(
color_family => findColors.includes(color_family)
)
)
This is returning no results when it should return 2 results. Can someone point me in the right direction?
In addition to the typo, the param to the find argument is an object with color_family:
const res = arr.filter(x => x.acf.product_colors.find(col => {
return findColors.includes(col.color_family);
}))