How to groupBy an attribute inside the second array with javascript - javascript

I am trying to convert an array object to a new set of arrays grouped by their value. In this case, it is the date value.
What I have tried in in the below code, but I didn't get the results of what I wanted. Can you please help me find the right solution for this problem?
INPUT
let array = [
{
"category": {
"code": "1558950145861"},
"lines": [
{
"date": "2020-02-26",
"price": 9260,
"dispo": 5
},
{
"date": "2020-02-29",
"price": 6300,
"dispo": 9
},
{
"date": "2020-04-01",
"price": 7700,
"dispo": 23
}
]
},
{
"category": {
"code": "1788858954441"
},
"lines": [
{
"date": "2020-02-26",
"price": 6260,
"dispo": 2
},
{
"date": "2020-02-29",
"price": 5500,
"dispo": 4
},
{
"date": "2020-04-01",
"price": 840,
"dispo": 7
}
]
}
];
Desired OUTPUT
[{
"date": "2020-02-26",
"lines": [{
"price": 9260,
"dispo": 5
}, {
"price": 6260,
"dispo": 2
}]
}, {
"date": "2020-02-29",
"lines": [{
"price": 6300,
"dispo": 9
}, {
"price": 5500,
"dispo": 4
}]
}, {
"date": "2020-04-01",
"lines": [{
"price": 7700,
"dispo": 23
}, {
"price": 840,
"dispo": 7
}]
}]
code that I wrote
var result = (_array)
.groupBy(x => {
for (let j = 0; j < x.lines.length; j += 1) {
return x.lines[j].date;
}
})
.map((value, key) => ({
date: key,
lines: value
})).value();
I want my code to generate the desired output, but it isn't doing that. What might I be doing wrong?

try this
let array = [{ "category": { "code": "1558950145861" }, "lines": [{ "date": "2020-02-26", "price": 9260, "dispo": 5 }, { "date": "2020-02-29", "price": 6300, "dispo": 9 }, { "date": "2020-04-01", "price": 7700, "dispo": 23 }] }, { "category": { "code": "1788858954441" }, "lines": [{ "date": "2020-02-26", "price": 6260, "dispo": 2 }, { "date": "2020-02-29", "price": 5500, "dispo": 4 }, { "date": "2020-04-01", "price": 840, "dispo": 7 }] }]
const groupBy = (arr) => arr.reduce((acc, ele)=>( (acc[ele.date] = acc[ele.date] || []).push(ele), acc),{})
const all = [].concat(...array.map(ele=> ele.lines))
const format = ele => ele.map(({price, dispo})=>({price, dispo}))
console.log(Object.entries(groupBy(all)).map(([date, lines])=> ({date, lines: format(lines)})))

Try something like this :
var out = {}
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i]["lines"].length; j++) {
let e = array[i]["lines"][j];
if (!out[e["date"]]) {
out[e["date"]] = [];
}
out[e["date"]].push({"price": e["price"], "dispo": e["dispo"]});
}
}
var result = [];
for (let k in out) {
result.push({"date": k, "lines": out[k]});
}
The result variable has the desired output format.

You don't appear to need the category value, so first I'd merge the lines into a single array where you can groupBy from there:
// using your input called 'array'
// First collect just the line arrays:
var arrayOfLineArrays=array.map(category => category.lines);
// Merge them into one bigger array:
var allLines = _.flatten(arrayOfLineArrays);
// Now you can groupBy with ease:
var dateGroupsObject = _(allLines).groupBy(line => line.date);
// And map to an array:
var result = _.values(_.mapObject(dateGroupsObject, (value, key) => ({
date: key,
lines: value
}))));

Related

Find every possibilitie in an array of object comparing key values

I have an specific math formula which receives three parameters and I'm trying to get from an array of object all the possibilities to run this math formula.
It's regards to sports.
Imagine a match where there are 3 possibility: Team A (win) - Team B (win) - Draw.
3 bet websites are dealing with this event. But the 3 of them have different odds values for this match.
I want to run those 3 bet websites to get all posibilities I can have for this event. Never getting more than one odd from the same bet website.
Example:
Website A: team A (win)
Website B: team B (win)
Website C: draw
I'm using JavaScript for that.
Thank you in advance for you time and support.
Really appreciate that.
Here is an example of data I have to get these possibilities.
Each obj is a website and into the object, the odds are on the key "outcomes".
The array of object here has 3 objects, but it can have more
[
{
"key": "betmgm",
"title": "BetMGM",
"last_update": "2022-12-14T04:30:40Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 138
},
{
"name": "Tottenham Hotspur",
"price": 200
},
{
"name": "Draw",
"price": 225
}
]
}
]
},
{
"key": "barstool",
"title": "Barstool Sportsbook",
"last_update": "2022-12-14T04:30:22Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
},
{
"key": "twinspires",
"title": "TwinSpires",
"last_update": "2022-12-14T04:17:45Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
}
]
I would like to receive an array with the possibilities like this:
[
{
"bookMaker": "TwinSpires",
"name": "Tottenham Hotspur",
"price": 230,
},
{
"bookMaker": "Barstool Sportsbook",
"name": "AC Milan",
"price": 130,
},
{
"bookMaker": "BetMGM",
"name": "Draw",
"price": 225,
}
]
The algorithm is quite simple. First, we take all the outcomes of the first Bet website. We shuffle them randomly.
Then we simply loop through the JSON object, which is a list of bet websites, not to mention the fact that both the number of outcomes must be the same as the number of bet websites. We assign for each bet website the next item of the shuffled outcomes. We log it to the console.
Here is the algorithm:
var data = [
{
"key": "betmgm",
"title": "BetMGM",
"last_update": "2022-12-14T04:30:40Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 138
},
{
"name": "Tottenham Hotspur",
"price": 200
},
{
"name": "Draw",
"price": 225
}
]
}
]
},
{
"key": "barstool",
"title": "Barstool Sportsbook",
"last_update": "2022-12-14T04:30:22Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
},
{
"key": "twinspires",
"title": "TwinSpires",
"last_update": "2022-12-14T04:17:45Z",
"markets": [
{
"key": "h2h",
"outcomes": [
{
"name": "AC Milan",
"price": 130
},
{
"name": "Tottenham Hotspur",
"price": 220
},
{
"name": "Draw",
"price": 230
}
]
}
]
}
];
start(data);
function start(data) {
var outcomes = data[0].markets[0].outcomes;
if (data.length != outcomes.length) {
alert("Invalid data!");
return;
}
var results = createResults(data);
printResults(results);
}
function createResults(data) {
var outcomes = data[0].markets[0].outcomes;
var newOutcomesNames = shuffleOutcomes(outcomes);
var results = [];
for (var i = 0; i < data.length; i++) {
var currentBetWebsite = data[i];
var currentResult = {};
var currentOutcomes = currentBetWebsite.markets[0].outcomes;
currentResult.bookMaker = currentBetWebsite.title;
currentResult.name = newOutcomesNames[i];
for (var j = 0; j < newOutcomesNames.length; j++) {
if (newOutcomesNames[i] == currentOutcomes[j].name) {
currentResult.price = currentOutcomes[j].price;
}
}
results.push(currentResult);
}
return results;
}
function printResults(results) {
console.log(results);
}
function shuffleOutcomes(outcomes) {
var parsedOutcomes = parseOutcomesNames(outcomes);
var outcomesLength = parsedOutcomes.length;
var newOutcomes = [];
for (var i = 0; i < outcomesLength; i++) {
var random = Math.floor(Math.random() * (outcomesLength - i));
newOutcomes.push(parsedOutcomes[random]);
parsedOutcomes.splice(random, 1);
}
return newOutcomes;
}
function parseOutcomesNames(outcomes) {
var outcomesNames = outcomes.map(o => o.name);
return outcomesNames;
}
Let me know, if you need any further assistance.

Javascript: How to subtotal values in list of { value, date } by time period?

I have a list of objects like this:
const rawData = [
{
"quantity": 44000,
"date": "2017-10-24"
},
{
"quantity": 44000,
"date": "2017-10-24"
},
{
"quantity": 44000,
"date": "2017-10-27"
},
{
"quantity": 44000,
"date": "2017-10-27"
},
{
"quantity": 44000,
"date": "2017-11-16"
}
]
I want to sum the quantities that belong in the same time period.
For instance, applying a monthly period, I would like to obtain a list like this:
dataTotalledByMonth:
[
{
"quantity": 176000,
"period": "2017-10"
},
{
"quantity": 44000,
"period": "2017-11"
}
]
I want to come up with a general solution that will allow me to switch to different periods (annually, weekly, quarterly, etc) and get the processed list dynamically.
While #R4ncid's solution works, I have an idea for a simpler code, which I deem more easier to follow:
const rawData = [{
"quantity": 44000,
"date": "2017-10-24"
},
{
"quantity": 44000,
"date": "2017-10-24"
},
{
"quantity": 44000,
"date": "2017-10-27"
},
{
"quantity": 44000,
"date": "2017-10-27"
},
{
"quantity": 44000,
"date": "2017-11-16"
}
];
const final = {};
rawData.forEach(row => {
// take just the first 2 date elements (year + month)
const period = row.date.split('-').slice(0, -1).join('-');
if (final[period]) {
final[period].quantity += row.quantity;
} else {
final[period] = {
period,
quantity: row.quantity
};
}
});
console.log(final);
console.log(Object.values(final));
something like this?
const rawData = [
{
"quantity": 44000,
"date": "2017-10-24"
},
{
"quantity": 44000,
"date": "2017-10-24"
},
{
"quantity": 44000,
"date": "2017-10-27"
},
{
"quantity": 44000,
"date": "2017-10-27"
},
{
"quantity": 44000,
"date": "2017-11-16"
}
]
const calculateTotal = keyExtractor => data =>
Object.values(data.reduce((res, item) => {
const date = keyExtractor(item)
return {
...res,
[date]: {
...res[date],
date,
quantity: (res[date]?.quantity || 0) + item.quantity
}
}
}, {}))
const annualCalculateTotal = calculateTotal(({date}) => date.substring(0, 4))
const monthlyCalculateTotal = calculateTotal(({date}) => date.substring(0, 7))
const afterAndBeforedateKeyGenerator = date => item => new Date(date) > new Date(item.date)? `before ${date}`: `after ${date}`
console.log(annualCalculateTotal(rawData))
console.log(monthlyCalculateTotal(rawData))
console.log(calculateTotal(afterAndBeforedateKeyGenerator('2017-10-27'))(rawData))

Group array of objects inside nested Array and add its total to a new Array [duplicate]

This question already has answers here:
JavaScript - Sum the values of same ids of different objects in the array of objects
(9 answers)
Closed 1 year ago.
I have an array of object with different tax rate and its value. I'm trying to combine all values with same tax rate into single object. Below is my code
const arr = [
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 4.01,
},
{
"name": "SGST 2.5%",
"total": 4.01,
},
],
},
{
"taxes": [
{
"name": "CGST 6%",
"total": 10,
},
{
"name": "SGST 6%",
"total": 10,
},
],
},
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 16.42,
},
{
"name": "SGST 2.5%",
"total": 16.42,
},
],
},
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 0,
},
{
"name": "SGST 2.5%",
"total": 0,
},
],
},
{
"taxes": [
{
"name": "CGST 6%",
"total": 12,
},
{
"name": "SGST 6%",
"total": 12,
},
],
},
];
const result = arr.map(item => {
return Object.values(item.taxes.reduce((r, { name, total }) => {
(r[name] || (r[name] = [name, 0]))[1] += total;
return r;
}, {}));
})
console.log(result);
I have searched and got reduce function which is working but I'm not able to make it to work with the nested arrays.
Kindly tolerate with my ability as I'm not at all familiar with the reduce function how it works.
What I wanted it will return me a new Array like
{ "CGST 2.5%": 20.43, "SGST 2.5%": 20.43, "CGST 6%": 22, "SGST 6%": 22 }
Simpler solution I can think of:
const result = {}
arr.forEach(el => {
el.taxes.forEach(tax => {
result[tax.name] = (result[tax.name] || 0)+ tax.total
})
})
const solution = Object.entries(result).map(el => ({name: el[0], total: el[1]}))
console.log(solution)
#Atal Shrivastava, I appreciate your attempt, This is very simple solation, 1st check if entry exist or not, if not create entry else increase entry...
Code:
const arr = [{ "taxes": [{ "name": "CGST 2.5%", "total": 4.01 }, { "name": "SGST 2.5%", "total": 4.01 },] }, { "taxes": [{ "name": "CGST 6%", "total": 10, }, { "name": "SGST 6%", "total": 10 },] }, { "taxes": [{ "name": "CGST 2.5%", "total": 16.42 }, { "name": "SGST 2.5%", "total": 16.42 },] }, { "taxes": [{ "name": "CGST 2.5%", "total": 0, }, { "name": "SGST 2.5%", "total": 0, },] }, { "taxes": [{ "name": "CGST 6%", "total": 12, }, { "name": "SGST 6%", "total": 12 },] }];
const result = arr.reduce((result, { taxes }) => {
for (const { name, total } of taxes)
if (result[name])
result[name] += total
else
result[name] = total
return result;
}, {})
console.log(result);

Flatten an object using lodash

I have below this nested object
I need to create an array using this object containing keys. And if keys are object then it should use .dot syntax. and if it is an array then it should give me key.0.keyName. Is it possible to do so?
Output
[
"AllowIPNPayment",
"AllowOnlinePayment",
"MetaData.CreateTime",
"MetaData.LastUpdatedTime",
"CustomField.0.DefinitionId",
"CustomField.0.Name",
"CustomField.0.Type",
...
]
What I have tried is just ugly and does give me expected result. If it is possible with more concise way.
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 }
let object = {}
for (let k in invoiceObject) {
if (typeof invoiceObject[k] === "object") {
object[k] = {};
for (let l in invoiceObject[k]) {
object[k][l] = "";
}
} else if (typeof invoiceObject[k] === "array") {
object[k] = [];
for (let l in invoiceObject[k][0]) {
object[k][l] = "";
}
} else {
object[k] = "";
}
}
console.log(object)
You can create a recursive function (getSchema) that checks if a value (val) is an object (arrays included), iterate it with _.flatMap(), and collects the keys until it hits a value which is not an object. It then joins the collected keys and returns the string.
const getSchema = (val, keys = []) =>
_.isObject(val) ? // if it's an object or array
_.flatMap(val, (v, k) => getSchema(v, [...keys, k])) // iterate it and call fn with the value and the collected keys
:
keys.join('.') // return the joined keys
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 }
const result = getSchema(invoiceObject)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Without lodash, the main change is to use Object.entries() to get an array of [key, value] pairs, since Array.flatMap() can't iterate objects:
const getSchema = (val, keys = []) =>
typeof val === 'object' && val !== null ? // if it's an object or array
Object.entries(val) // get [key, value] pairs of object/array
.flatMap(([k, v]) => getSchema(v, [...keys, k])) // iterate it and call fn with the value and the collected keys
:
keys.join('.') // return the joined keys
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 }
const result = getSchema(invoiceObject)
console.log(result)
inspired by the answer given in this post and understanding you just want to get the property-names, not values, you could do it like this. sorry, this uses plain javascript.
function flattenObjectToKeyArray(ob) {
var toReturn = [];
for (var prop in ob) {
if (!ob.hasOwnProperty(prop)) continue;
if ((typeof ob[prop]) == 'object' && ob[prop] !== null) {
var flatObject = flattenObjectToKeyArray(ob[prop]);
for (var idx = 0; idx < flatObject.length; idx++) {
toReturn.push(prop + '.' + flatObject[idx]);
}
} else {
toReturn.push(prop);
}
}
return toReturn;
}
You could solve this with a recursive function. The function below keeps track of the current keys, and joins them as soon as an end point is reached (a non-object or empty object/array).
const invoiceObject = { "AllowIPNPayment": false, "AllowOnlinePayment": false, "AllowOnlineCreditCardPayment": false, "AllowOnlineACHPayment": false, "domain": "QBO", "sparse": false, "Id": "16", "SyncToken": "1", "MetaData": { "CreateTime": "2020-03-25T15:10:40-07:00", "LastUpdatedTime": "2020-03-26T11:06:49-07:00" }, "CustomField": [{ "DefinitionId": "1", "Name": "Crew #", "Type": "StringType" }], "DocNumber": "1007", "TxnDate": "2020-03-03", "CurrencyRef": { "value": "USD", "name": "United States Dollar" }, "LinkedTxn": [{ "TxnId": "32", "TxnType": "Payment" }], "Line": [{ "Id": "1", "LineNum": 1, "Description": "Custom Design", "Amount": 750, "DetailType": "SalesItemLineDetail", "SalesItemLineDetail": { "ItemRef": { "value": "4", "name": "Design" }, "UnitPrice": 75, "Qty": 10, "TaxCodeRef": { "value": "NON" } } }, { "Amount": 750, "DetailType": "SubTotalLineDetail", "SubTotalLineDetail": {} } ], "TxnTaxDetail": { "TotalTax": 0 }, "CustomerRef": { "value": "13", "name": "uiool" }, "CustomerMemo": { "value": "Thank you for your business and have a great day!" }, "SalesTermRef": { "value": "3" }, "DueDate": "2020-04-02", "TotalAmt": 750, "ApplyTaxAfterDiscount": false, "PrintStatus": "NeedToPrint", "EmailStatus": "NotSet", "BillEmail": { "Address": "uiikoool" }, "Balance": 450 };
function getDotKeys(item, keys = []) {
const isObject = item && typeof item == "object";
if (!isObject) return Array.of(keys.join("."));
const pairs = Array.isArray(item)
? item.map((value, index) => [index, value])
: Object.entries(item);
const isEmpty = !pairs.length;
if (isEmpty) return Array.of(keys.join("."));
const result = [];
for (const [key, value] of pairs) {
const dotKeys = getDotKeys(value, [...keys, key]);
result.push(...dotKeys);
}
return result;
}
console.log(getDotKeys(invoiceObject));
This does produce a different result than what you have in your question, since your solution stops at the second level for objects and third level for arrays. This solution also includes more then only index 0.

copy from one object, change keys but keep the same values

Hi I want to copy a JavaScript object that lives in an external json file. It looks like this:
and via the code I want to change the keys on each array without changing the values of it. The values for the last key needs be an array instead of just vales
{ "items": [
{ "namezz": "Bike", "price": 100 },
{ "namezz": "TV", "price": 700 },
{ "namezz": "Album", "price": 10 },
{ "namezz": "Book", "price": 5 },
{ "namezz": "Phone", "price": 500 },
{ "namezz": "Computer", "price": 1000 },
{ "namezz": "Keyboard", "price": 25 }
]
}
It needs to looks like this:
[
{ "name": "Bike", "data": [100] },
{ "name": "TV", "data": [700] },
{ "name": "Album", "data": [10] },
{ "name": "Book", "data": [5] },
{ "name": "Phone", "data": [500] },
{ "name": "Computer", "data": [1000] },
{ "name": "Keyboard", "data": [25] }
]
code that I've tried:
const itemNames = simple.map((xxx) => {
return ("name" + xxx.namezz + "data: [" + xxx.price + "]")
})
You're on the right track with the map() method. The way you've used map() will result in an array of strings. Here's an example of using map() to get the output you requested (new array of objects).
const myObject = {
"items": [{
"namezz": "Bike",
"price": 100
},
{
"namezz": "TV",
"price": 700
},
{
"namezz": "Album",
"price": 10
},
{
"namezz": "Book",
"price": 5
},
{
"namezz": "Phone",
"price": 500
},
{
"namezz": "Computer",
"price": 1000
},
{
"namezz": "Keyboard",
"price": 25
}
]
};
const result = myObject.items.map(x => ({ name: x.namezz, data: [x.price] }));
console.log(result);
Problem with your code is returning string whereas you need a object, i.e
return { name:xxx.namezz , data: [xxx.price] }
Alternatively you can use map and destructuring
let obj = { "items": [{ "namezz": "Bike", "price": 100 },{ "namezz": "TV", "price": 700 },{ "namezz": "Album", "price": 10 },{ "namezz": "Book", "price": 5 },{ "namezz": "Phone", "price": 500 },{ "namezz": "Computer", "price": 1000 },{ "namezz": "Keyboard", "price": 25 }]}
let final = obj.items.map(({ price, namezz }) => ({ namezz, data: [price] }))
console.log(final)

Categories

Resources