How to read values and sum over a dynamic array? - javascript

I have an JSON like this
"result": [{
"channel": "A",
"mkp": "ABC",
"qtd": 6,
"total": 2938.2,
"data": "2019-02-16",
"time": "22:30:40"
}, {
"channel": "C",
"mkp": "DEF",
"qtd": 1545,
"total": 2127229.64,
"data": "2019-02-20",
"time": "17:19:49"
}, {
"channel": "C",
"mkp": "JKL",
"qtd": 976,
"total": 1307328.37,
"data": "2019-02-20",
"time": "17:19:53"
}, {
"channel": "U",
"mkp": "PQR",
"qtd": 77,
"total": 98789.87,
"data": "2019-02-20",
"time": "16:12:31"
}, {
"channel": "U",
"mkp": "STU",
"qtd": 427,
"total": 433206.62,
"data": "2019-02-20",
"time": "17:04:27"
}
]
I need to sum the QTD, the total and return the newest data + time when the channel is the same (eg.: Channel C and U have 2 entries), if it's not so I only will display the values, but I can't figure it out how could I iterate and do these math. Someone could help?
A sample of what I want:
"A": [{
"qtd": 6,
"total": 2938.20,
"dateTime": 2019 - 02 - 16 22: 30: 40 "
}],
"C": [{
"qtd": 2.521,
"total": 3434558.01,
"dateTime": 2019 - 02 - 20 17: 19: 53 "
}],
"U": [{
"qtd": 504,
"total": 531996,
49,
"dateTime": 2019 - 02 - 20 17: 04: 27 "
}]
Currently I separated the values using filter like this:
this.channelA = this.receivedJson.filter(({ channel }) => channel === "A");

You could use reduce method and return one object with object as values.
const data = [{"channel":"A","mkp":"ABC","qtd":6,"total":2938.2,"data":"2019-02-16","time":"22:30:40"},{"channel":"C","mkp":"DEF","qtd":1545,"total":2127229.64,"data":"2019-02-20","time":"17:19:49"},{"channel":"C","mkp":"JKL","qtd":976,"total":1307328.37,"data":"2019-02-20","time":"17:19:53"},{"channel":"U","mkp":"PQR","qtd":77,"total":98789.87,"data":"2019-02-20","time":"16:12:31"},{"channel":"U","mkp":"STU","qtd":427,"total":433206.62,"data":"2019-02-20","time":"17:04:27"}]
const res = data.reduce((r, {channel, qtd, total, data, time}) => {
const dateTime = `${data} ${time}`
if(!r[channel]) r[channel] = {qtd, total, dateTime}
else {
r[channel].total += total
r[channel].qtd += qtd;
r[channel].dateTime = dateTime
}
return r;
}, {})
console.log(res)

You an use reduce to group the values based on channel like this:
const input = [{"channel":"A","mkp":"ABC","qtd":6,"total":2938.2,"data":"2019-02-16","time":"22:30:40"},{"channel":"C","mkp":"DEF","qtd":1545,"total":2127229.64,"data":"2019-02-20","time":"17:19:49"},{"channel":"C","mkp":"JKL","qtd":976,"total":1307328.37,"data":"2019-02-20","time":"17:19:53"},{"channel":"U","mkp":"PQR","qtd":77,"total":98789.87,"data":"2019-02-20","time":"16:12:31"},{"channel":"U","mkp":"STU","qtd":427,"total":433206.62,"data":"2019-02-20","time":"17:04:27"}]
const merged = input.reduce((acc, { channel, qtd, total, data, time }) => {
acc[channel] = acc[channel] || [{ qtd: 0, total: 0, dateTime:'' }];
const group = acc[channel][0];
group.qtd += qtd;
group.total += total;
const dateTime = `${data} ${time}`
if(dateTime > group.dateTime)
group.dateTime = dateTime;
return acc;
}, {})
console.log(merged)

Related

Create new array with new keys and nested object from single array

I'm trying to organise data from an api that returns the following json:
[
{
"0": "THURSDAY 25th MARCH",
"1": "",
"2": ""
},
{
"0": "Snow Patrol",
"1": "Press Conference",
"2": "16:00 - 19:35"
},
{
"0": "",
"1": "",
"2": ""
},
{
"0": "FRIDAY 26th MARCH",
"1": "",
"2": ""
},
{
"0": "Arctic Moneys",
"1": "Concert",
"2": "11:55 - 12:40"
},
{
"0": "Rush",
"1": "Practice Session",
"2": "13:05 - 13:50"
}
]
The api returns an array with only numbers as keys and the next date starts after and empty object.
Into an organised array like so:
[
{
"date": "THURSDAY 25th MARCH",
"events": [
{
"band": "Snow Patrol",
"type": "Press Conference",
"time": "16:00 - 19:35"
}
]
},
{
"date": "FRIDAY 26th MARCH",
"events": [
{
"band": "Arctic Moneys",
"type": "Concert",
"time": "11:55 - 12:40"
},
{
"band": "Rush",
"type": "Practice Session",
"time": "13:05 - 13:50"
}
]
}
]
Any help would be much appreciated!
Cheers!
You could create an array of each object and check if all vlaues are empty strings or the last two ones.
The continue or build a new date object and add later all events to the last object.
const
data = [{ 0: "THURSDAY 25th MARCH", 1: "", 2: "" }, { 0: "Snow Patrol", 1: "Press Conference", 2: "16:00 - 19:35" }, { 0: "", 1: "", 2: "" }, { 0: "FRIDAY 26th MARCH", 1: "", 2: "" }, { 0: "Arctic Moneys", 1: "Concert", 2: "11:55 - 12:40" }, { 0: "Rush", 1: "Practice Session", 2: "13:05 - 13:50" }],
result = data.reduce((r, o) => {
const a = Object.assign([], o);
if (!a.join('')) return r;
if (!a.slice(1).join('')) {
r.push({ date: a[0], events: [] });
} else {
const [band, type, time] = a;
r[r.length - 1].events.push({ band, type, time });
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Transform an object of objects to an array (special example)

I am trying to transform an object of objects into an array of objects. Basically I want to transform this:
sales_over_time_week: {
"1": {
"orders": 96,
"total": 270240
},
"2": {
"orders": 31,
"total": 74121
}
}
into this:
[
{name: 1, orders:96, total:270240},
{name:2, orders:31, total: 74121}
]
To just transform it normally I would do this
var myData = Object.keys(items).map(key => {
return items[key];
});
and it would give me
[
{1: {orders: 31, total: 74121}},
{2: {orders: 52, total: 180284}}
]
but my example is a bit special
You can use Object.entries with .map()
let data = {
"1": {
"orders": 96,
"total": 270240
},
"2": {
"orders": 31,
"total": 74121
}
};
let result = Object.entries(data).map(([key, value]) => ({name: key, ...value}));
console.log(result);
Try
Object.keys(data).map(k=> ({name:+k, ...data[k]}));
data = {
"1": {
"orders": 96,
"total": 270240
},
"2": {
"orders": 31,
"total": 74121
}
}
let r = Object.keys(data).map(k=> ({name:+k, ...data[k]}));
console.log(r);

How can I merge two array of objects with two different sizes by using key, value pair to merge them into one array?

I have two array of objects that looks this in JSON format:
{
"Arr1":
[
{ "_id": "firstSub1", "count": 1, "price": 4 },
{ "_id": "firstSub2", "count": 2, "price": 7 },
{ "_id": "firstSub3", "count": 3, "price": 1 }
{ "_id": "firstSub4", "count": 4, "price": 1 }
],
"Arr2":
[
{ "name": "firstSub1", "date": 05 / 20 / 1998, "type": sometype1 },
{ "name": "firstSub2" "date": 12 / 22 / 2011, "type": sometype2 },
{ "name": "firstSub3", "date": 09 / 23 / 2004, "type": sometype3 }
{ "name": "firstSub9", "date": 09 / 23 / 2004, "type": sometype9 }
]
//Desired Output
"finalArray":
[
{ "name": "firstSub1", "date": 05 / 20 / 1998, "type": sometype1, "count": 1, "price": 4 },
{ "name": "firstSub2" "date": 12 / 22 / 2011, "type": sometype2, "count": 2, "price": 7 },
{ "name": "firstSub3", "date": 09 / 23 / 2004, "type": sometype3, "count": 3, "price": 1 },
{ "name": "firstSub9", "date": 09 / 23 / 2004, "type": sometype9 },
{ "_id": "firstSub4", "count": 4, "price": 1 }
]
}
I need to compare _id in the first array and see if there is a match with name in the Arr2 and match them if _id === name.
I have tried using lodash and its undescores, and mapping functions like this:
mergeArray() {
.... //pulling data
let Arr1 = data['Arr1Data'];
let Arr2 = data['Arr2Data'];
let finalArray = Arr2.map((e, _) =>
(_ = Arr1.find((q) => e.name === q._id)) ?
{ ...e, ..._ } : e)
console.log(finalArray)
}
All of the data from Arr2 is coming back and merging with only half of the data Arr1 my data is not coming back with the desired output...how can i map these two arrays and have a union and intersection?
Using vanilla Js, you can get an array of unique _id and name from both arrays, loop throught it and join the object from both arrays that matches the current id in the iteration :
Deduped array of ids and names :
const ids = [...new Set([...Arr1.map(e => e._id), ...Arr2.map(e => e.name)])];
Loop to join elements from both arrays :
const result = ids.map(e => ({
...Arr1.find(o => o._id === e),
...Arr2.find(o => o.name === e)
}))
const Arr1 = [{"_id": "firstSub1","count": 1,"price": 4},{"_id": "firstSub2","count": 2,"price": 7},{"_id": "firstSub3","count": 3, "price": 1}, {"_id": "firstSub4","count": 4,"price": 1}];
const Arr2 = [{"name": "firstSub1","date": "05 / 20 / 1998","type": "sometype1"}, {"name": "firstSub2","date": "12 / 22 / 2011","type": "sometype2"}, {"name": "firstSub3","date": "09 / 23 / 2004","type": "sometype3"}, {"name": "firstSub9","date": "09 / 23 / 2004","type": "sometype9"}];
const ids = [...new Set([...Arr1.map(e => e._id), ...Arr2.map(e => e.name)])];
const result = ids.map(e => ({
...Arr2.find(o => o.name === e),
...Arr1.find(o => o._id === e)
}))
console.log(result)
EDIT :
You can tweak the returned object in .map() to remove properties ( like _id) :
const Arr1 = [{"_id": "firstSub1","count": 1,"price": 4},{"_id": "firstSub2","count": 2,"price": 7},{"_id": "firstSub3","count": 3, "price": 1}, {"_id": "firstSub4","count": 4,"price": 1}];
const Arr2 = [{"name": "firstSub1","date": "05 / 20 / 1998","type": "sometype1"}, {"name": "firstSub2","date": "12 / 22 / 2011","type": "sometype2"}, {"name": "firstSub3","date": "09 / 23 / 2004","type": "sometype3"}, {"name": "firstSub9","date": "09 / 23 / 2004","type": "sometype9"}];
const ids = [...new Set([...Arr1.map(e => e._id), ...Arr2.map(e => e.name)])];
const result = ids.map(e => {
const obj = {
...Arr2.find(o => o.name === e),
...Arr1.find(o => o._id === e)
}
if(obj.name && obj._id) delete obj._id;
return obj;
})
console.log(result)
You can use lodash's _.flow() to create a function that combines the arrays, groups them by name or _id (whatever is found on the object). If the a group contains more than 1 item, it's merged to a single object, and the _id property is omitted.
const { flow, partialRight: pr, concat, groupBy, map, merge, has, head, omit } = _
const fn = flow(
concat, // combine to a single array
pr(groupBy, o => o.name || o._id), // group by the value of name or _id
pr(map, o => o.length === 1 ? head(o) : _.omit( // if a group contains 2 items merge them, and remove _id
merge({}, ...o),
'_id'
)),
)
const Arr1 = [{"_id": "firstSub1","count": 1,"price": 4},{"_id": "firstSub2","count": 2,"price": 7},{"_id": "firstSub3","count": 3, "price": 1}, {"_id": "firstSub4","count": 4,"price": 1}]
const Arr2 = [{"name": "firstSub1","date": "05 / 20 / 1998","type": "sometype1"}, {"name": "firstSub2","date": "12 / 22 / 2011","type": "sometype2"}, {"name": "firstSub3","date": "09 / 23 / 2004","type": "sometype3"}, {"name": "firstSub9","date": "09 / 23 / 2004","type": "sometype9"}]
const result = fn(Arr2, Arr1)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
One solution is to use Array.reduce() starting with an accumulator equal to a copy of Arr2 (JSON.parse(JSON.stringify(Arr2))) so we don't mutate the original array Arr2. Now, while iterating over Arr1, if we found a match then we add the related properties using Object.assign() to the associated object on the accumulator, otherwise we put the entire object on the accumulator:
const Arr1 = [
{"_id": "firstSub1", "count": 1, "price": 4},
{"_id": "firstSub2", "count": 2, "price": 7},
{"_id": "firstSub3", "count": 3, "price": 1},
{"_id": "firstSub4", "count": 4, "price": 1}
];
const Arr2 = [
{"name": "firstSub1", "date": "05/20/1998", "type": "sometype1"},
{"name": "firstSub2", "date": "12/22/2011", "type": "sometype2"},
{"name": "firstSub3", "date": "09/23/2004", "type": "sometype3"},
{"name": "firstSub9", "date": "09/23/2004", "type": "sometype9"}
];
let res = Arr1.reduce((acc, {_id, count, price}) =>
{
let fIdx = acc.findIndex(({name}) => name === _id);
if (fIdx >= 0)
Object.assign(acc[fIdx], {count, price});
else
acc.push({_id, count, price});
return acc;
}, JSON.parse(JSON.stringify(Arr2)));
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
You can sort by name and compare the i + 1 index name to validate if the i + 1 index and the i index should be merged or if the object doesn't have a pair for merging.
For example, sorting by name means that the next object/index will be the pair.
[{name: "firstSub1", count: 1}, {name: "firstSub1", date: "dd / mm / yyyy"}] // Pair found
or
[{name: "firstSub1", count: 1}, {name: "firstSub2", count: 1}] // There is no a pair
This is assuming there is max one pair
let obj = { "Arr1": [{ "_id": "firstSub1", "count": 1, "price": 4 }, { "_id": "firstSub2", "count": 2, "price": 7 }, { "_id": "firstSub3", "count": 3, "price": 1 }, { "_id": "firstSub4", "count": 4, "price": 1 } ], "Arr2": [{ "name": "firstSub1", "date": "05 / 20 / 1998", "type": "sometype1" }, { "name": "firstSub2", "date": "12 / 22 / 2011", "type": "sometype2" }, { "name": "firstSub3", "date": "09 / 23 / 2004", "type": "sometype3" }, { "name": "firstSub9", "date": "09 / 23 / 2004", "type": "sometype9" } ]};
// All objects in one array.
let merge = [...obj.Arr2,
// The map is to change _id by name, this is used later.
...obj.Arr1.map(({_id, count, price}) => ({name: _id, count, price}))]
.sort((a, b) => a.name.localeCompare(b.name));
// This approach doesn't mutate the source objects.
let result = [];
for (let i = 0; i < merge.length;) {
if (merge[i + 1] && merge[i + 1].name === merge[i].name) {
result.push(Object.assign(Object.create(null), merge[i], merge[i + 1]));
i++;
} else result.push(merge[i]);
i++;
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Count how many objects in an array has a certain value (JavaScript)

I have an array of objects, like so:
[
{
"_id": "5b09cc3495cb6c0487f1166b",
"name": "ccc",
"email": "ccc#gmail.com",
"phone": "790467522",
"kidsNo": "1",
"adultsNo": "1",
"fullDate": "2018/5/1",
"year": "2018",
"month": "5",
"day": "1",
"chosenHour": "11:00",
"chosenRoom": "x",
"__v": 0
},
{
"_id": "5b09cc6095cb6c0487f1166c",
"name": "asd",
"email": "asd#asd.pl",
"phone": "790467522",
"kidsNo": "2",
"adultsNo": "3",
"fullDate": "2018/5/1",
"year": "2018",
"month": "5",
"day": "1",
"chosenHour": "12:00",
"chosenRoom": "x",
"__v": 0
},
{
"_id": "5b0b1560c7b4fd0c33b2d52e",
"name": "dddd",
"email": "dddd#ddd.pl",
"phone": "123123112",
"kidsNo": "2",
"adultsNo": "1",
"fullDate": "2018/5/17",
"year": "2018",
"month": "5",
"day": "17",
"chosenHour": "11:00",
"chosenRoom": "x",
"__v": 0
}
]
In the future this array will contain much more objects.
I'm trying to solve this using map and for it seems to be quite complicated.
That's the challenge:
how I can count how many objects have certain value? How can I get to know how many times someone booked something to day===1? The best result would be an array like this:
[{dayOne: 2}, {dayTwo: 5}, {dayThree:1}.......and so on],
where value is the value of how many times a day was booked(key), hence how many times certain object(with certain value) has appeared in the array?
Thank you in advance!
To count objects by a condition, you can use .filter --
let firstDayCount = arr.filter(x => x.day === "1").length;
To group the result by days, you can use .reduce --
let countByDays =
arr.reduce((res, { day }) => {
res[day] = res[day] || 0;
res[day] += 1;
return res;
}, {});
If you want to format your output, you can then use a dictionary of names --
let dayNames = { 1: "dayOne", 2: "dayTwo" /* and so on */}
let formattedResult =
Object.keys(countByDays)
.map(n => { [dayNames[n]]: countByDays[n] });
Note that using a .filter for counting creates an intermediate throw-away array. We're not storing a reference anywhere, so it has to be GCed soon, but if it really affects your performance measurably in a real-life scenario, you can use a .reduce instead -- something that is called "deforestation":)
let count = arr.reduce((cnt, el) => el.day === "1" ? cnt += 1 : cnt, 0);
It'll still create an intermediate anonymous object though -- a reducer function -- so if your profiler shows this place as a bottleneck, you might be best off using a for loop. As always in such cases, it's up to you to find the right spot between performance and readability in your own real-world scenarios.
To get result exactly in that format you can do this.
const objs = [
{
"_id": "5b09cc3495cb6c0487f1166b",
"name": "ccc",
"email": "ccc#gmail.com",
"phone": "790467522",
"kidsNo": "1",
"adultsNo": "1",
"fullDate": "2018/5/1",
"year": "2018",
"month": "5",
"day": "1",
"chosenHour": "11:00",
"chosenRoom": "x",
"__v": 0
},
{
"_id": "5b09cc6095cb6c0487f1166c",
"name": "asd",
"email": "asd#asd.pl",
"phone": "790467522",
"kidsNo": "2",
"adultsNo": "3",
"fullDate": "2018/5/1",
"year": "2018",
"month": "5",
"day": "1",
"chosenHour": "12:00",
"chosenRoom": "x",
"__v": 0
},
{
"_id": "5b0b1560c7b4fd0c33b2d52e",
"name": "dddd",
"email": "dddd#ddd.pl",
"phone": "123123112",
"kidsNo": "2",
"adultsNo": "1",
"fullDate": "2018/5/17",
"year": "2018",
"month": "5",
"day": "17",
"chosenHour": "11:00",
"chosenRoom": "x",
"__v": 0
}
]
const days = [['dayOne', 1], ['dayTwo', 2], ['dayThree', 3]];
const res = days.reduce((acc, v) => {
const obj = {};
obj[v[0]] = objs.filter(x => x.day == v[1]).length;
return acc.concat(obj);
}, []);
console.log(res);
Note that you will need to extend the days array for every day you want to include like that. So If you want to include all 31 possible days, you need this.
const objs = [
{
"_id": "5b09cc3495cb6c0487f1166b",
"name": "ccc",
"email": "ccc#gmail.com",
"phone": "790467522",
"kidsNo": "1",
"adultsNo": "1",
"fullDate": "2018/5/1",
"year": "2018",
"month": "5",
"day": "1",
"chosenHour": "11:00",
"chosenRoom": "x",
"__v": 0
},
{
"_id": "5b09cc6095cb6c0487f1166c",
"name": "asd",
"email": "asd#asd.pl",
"phone": "790467522",
"kidsNo": "2",
"adultsNo": "3",
"fullDate": "2018/5/1",
"year": "2018",
"month": "5",
"day": "1",
"chosenHour": "12:00",
"chosenRoom": "x",
"__v": 0
},
{
"_id": "5b0b1560c7b4fd0c33b2d52e",
"name": "dddd",
"email": "dddd#ddd.pl",
"phone": "123123112",
"kidsNo": "2",
"adultsNo": "1",
"fullDate": "2018/5/17",
"year": "2018",
"month": "5",
"day": "17",
"chosenHour": "11:00",
"chosenRoom": "x",
"__v": 0
}
]
const days = [['dayOne', 1], ['dayTwo', 2], ['dayThree', 3], ['dayFour', 4], ['dayFive', 5],
['daySix', 6], ['daySeven', 7], ['dayEight', 8], ['dayNine', 9], ['dayTen', 10],
['dayEleven', 11], ['dayTwelve', 12], ['dayThirten', 13], ['dayFourteen', 14],
['dayFifteen', 15], ['daySixteen', 16], ['daySeventeen', 17], ['dayEighteen', 18],
['dayNineteen', 19], ['dayTwenty', 20], ['dayTwentyone', 21], ['dayTwentytwo', 22],
['dayTwentythree', 23], ['dayTwentyfour', 24], ['dayTwentyfive', 25], ['dayTwentysix', 26],
['dayTwentyseven', 27], ['dayTwentyeight', 28], ['dayTwentynine', 29], ['dayThirty', 30],
['dayThirtyone', 31]];
const res = days.reduce((acc, v) => {
const obj = {};
obj[v[0]] = objs.filter(x => x.day == v[1]).length;
return acc.concat(obj);
}, []);
console.log(res);
Which in this example returns [{dayOne: 2}, {dayTwo: 0}, ..., {daySeventeen}: 1, {dayNineteen: 0}, ...]
An alternative is using the function reduce to group and count.
const array = [{"_id": "5b09cc3495cb6c0487f1166b","name": "ccc","email": "ccc#gmail.com","phone": "790467522","kidsNo": "1","adultsNo": "1","fullDate": "2018/5/1","year": "2018","month": "5","day": "1","chosenHour": "11:00","chosenRoom": "x","__v": 0},{"_id": "5b09cc6095cb6c0487f1166c","name": "asd","email": "asd#asd.pl","phone": "790467522","kidsNo": "2","adultsNo": "3","fullDate": "2018/5/1","year": "2018","month": "5","day": "1","chosenHour": "12:00","chosenRoom": "x","__v": 0},{"_id": "5b0b1560c7b4fd0c33b2d52e","name": "dddd","email": "dddd#ddd.pl","phone": "123123112","kidsNo": "2","adultsNo": "1","fullDate": "2018/5/17","year": "2018","month": "5","day": "17","chosenHour": "11:00","chosenRoom": "x","__v": 0}],
result = Object.values(array.reduce((a, {day}) => {
let key = `day${day}`;
(a[key] || (a[key] = {[key]: 0}))[key]++;
return a;
}, {}));
console.log(result);

underscore not retaining keys on nested object

I have an object that looks like this:
var ingredientsObject = {
"Ingredients": [
{ "Section": "Ingredienser", "Name": "salt", "Value": 1, "Unit": "tsk" },
{ "Section": "Ingredienser", "Name": "olivolja", "Value": 1, "Unit": "msk" },
{ "Section": "Ingredienser", "Name": "lasagneplattor, (125 g) färska", "Value": 6, "Unit": "st" },
{ "Section": "Tomatsås", "Name": "salt", "Value": 0.5, "Unit": "tsk" },
{ "Section": "Tomatsås", "Name": "strösocker", "Value": 2, "Unit": "krm" }
{ "Section": "Béchamelsås", "Name": "salt", "Value": 0.5, "Unit": "tsk" },
{ "Section": "Béchamelsås", "Name": "smör", "Value": 2.5, "Unit": "msk" }
]
};
and I am trying to recalculate the value of each ingredient based on the number of servings specified using underscore.
I have tried using mapObject (http://underscorejs.org/#mapObject):
newIngredients = _.mapObject(ingredients.Ingredients, function (val, key) {
return val.Value / modifier;
});
but that returns an object that looks like this:
Object {0: 0.3333333333333333, 1: 0.3333333333333333, 2: 2, 3: 0.3333333333333333, 4: 50, 5: 66.66666666666667, 6: 0.16666666666666666, 7: 0.6666666666666666, 8: 0.25, 9: 0.3333333333333333, 10: 0.3333333333333333, 11: 0.16666666666666666, 12: 0.8333333333333334, 13: 0.16666666666666666, 14: 0.8333333333333334, 15: 1.6666666666666667, 16: 0.6666666666666666}
whereas what I actually want is the original object with only the values changed, as in:
var ingredientsObject = {
"Ingredients": [
{ "Section": "Ingredienser", "Name": "salt", "Value": 0.3333333333333333, "Unit": "tsk" },
{ "Section": "Ingredienser", "Name": "olivolja", "Value": 0.3333333333333333, "Unit": "msk" },
{ "Section": "Ingredienser", "Name": "lasagneplattor, (125 g) färska", "Value": 2, "Unit": "st" }
// and so on...
]
};
How do I achieve this?
Actually ingredients.Ingredients is an array, _.mapObejct expect a object as the first param. You can do this in underscore way:
_.mapObject(ingredientsObject, function(val, key) {
return _.map(val, function(ingredient) {
return _.extend(
{},
ingredient,
{
Value: ingredient.Value / modifier
}
)
})
})
Ok, based on the comments and suggestions I received, I came up with this solution:
newIngredients = _.each(ingredientsObject, function (list) {
_.each(list, function (item) {
item.Value = item.Value / modifier;
});
});
This modifies the value itself without modifying the object structure.
Thanks #nnnnnn for pointing me in the right direction.
Try:
newIngredients = _.map(ingredientsObject.Ingredients, function(item) {
return {
Section: item.Section,
Name: item.Name,
Value: item.Value / modifier,
Unit: item.Unit
};
});

Categories

Resources