Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a json file:
[
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
}, {
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}]
Now I want to get a list of the keys of each "name" object. At the end there should be ths list
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
and save it into an array.
What i have tried
var mydata = JSON.parse("jsonstring").ingredients;
hope this is understanable?
for each data in the array (map)
you want the ingredient part (.ingredients),
extract the keys (Object.keys)
and flatten the array (.flat())
array.map(a => a.ingredients).map(a => Object.keys(a)).flat();
You may prefer loop style. the only difference is flattening occurs with ... operator.
var results = [];
for (let a of array) {
results.push(...Object.keys(a.ingredients))
}
My proposition is :
'use strict'
const array = [
{
"name": "Cocktail 1",
"ingredients": {
"rum": 12,
"coke": 48
}
},
{
"name": "Cocktail 2",
"ingredients": {
"gin": 24,
"tonic": 60
}
}
]
const mydata = array.map((val) => {
return Object.keys(val.ingredients);
}).flat();
console.log(mydata)
// expected output: Array ["rum", "coke", "gin", "tonic"]
// Now you can get :
var mydata[0] = rum
var mydata[1] = coke
var mydata[2] = gin
var mydata[3] = tonic
Hope that help you? Thank
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
The community is reviewing whether to reopen this question as of 4 months ago.
Improve this question
I have here the data
var sampleArray = [
{ "Rating 1": -75 },
{ "Rating 2": -70 },
{ "Rating 3": 98 },
{ "Rating 4": -88 },
{ "Rating 5": 29 },
];
I want to sort it to output the following
Highest rating
Lowest rating
Rating that is near 0 (if there are 2 results, the positive will be chosen example:-1,1 then 1 will be chosen)
I'm stuck on getting the second value only which is the rating. I've tried the following codes to check if I can get the rating, but it shows the entire value of array 0
function topProduct(productProfitArray) {
return productProfitArray[0];
}
You can do this with reduce and a bit of logic to keep track of your min,max and diff from zero items
var sampleArray = [
{ "Rating 1": -75 },
{ "Rating 2": -70 },
{ "Rating 3": 98 },
{ "Rating 4": -88 },
{ "Rating 5": 29 },
];
var result = sampleArray.reduce( (acc,i) => {
var val= Object.values(i)[0];
if(val > acc.max)
{
acc.maxEntry = i;
acc.max = val;
}
if(val < acc.min)
{
acc.minEntry = i;
acc.min = val;
}
var diffFromZero = Math.abs(0-val);
if(diffFromZero < acc.diffFromZero)
{
acc.diffFromZero = diffFromZero;
acc.diffEntry = i;
}
return acc;
},{min:Number.POSITIVE_INFINITY, max:Number.NEGATIVE_INFINITY,diffFromZero:Number.POSITIVE_INFINITY});
console.log("min",result.minEntry);
console.log("max",result.maxEntry);
console.log("closeToZero",result.diffEntry);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to NodeJS and trying to reformate the JSON array which I get from MySQL database query.
I am having difficulty adding JSON Array into an array with a key such as before [] and after ["ABC":[]] using code.
skid.getSkidsForProcessingInvoice = async () => {
const query = `SELECT s.id as skidId, po.orderNumber,c.companyName FROM skid s INNER JOIN purchase_order po on s.purchaseOrderId = po.id WHERE s.process_status='PROCESSED' AND s.status = 'READY_FOR_INVOICE' AND s.close_status='Closed' ORDER By s.customerId,s.barCode`;
return await db.runQuery(query);
};
const skids = JSON.parse(JSON.stringify(await skidTask.getSkidsForProcessingInvoice()));
let rows = [];
skids.forEach(element => {
if (!rows[element.companyName]) {
// rows.push(element.companyName);
rows[element.companyName] = [];
}
rows[element.companyName].push(element);
});
skids:
[{
"skidId": 99,
"orderNumber": "iuryuouo",
"companyName": "ABC",
}, {
"skidId": 100,
"orderNumber": "iuryuouo",
"companyName": "ABC",
}, {
"skidId": 101,
"orderNumber": "etoiro",
"companyName": "XYZ",
}]
However, I am getting ["ABC", "XYZ"] as rows.
How can I form the rows as
[
"ABC":[
{
"skidId": 99,
"orderNumber": "iuryuouo",
"companyName": "ABC",
}, {
"skidId": 100,
"orderNumber": "iuryuouo",
"companyName": "ABC",
}
],
"XYZ":[
{
"skidId": 101,
"orderNumber": "etoiro",
"companyName": "XYZ",
}
]
]
As mentioned by #str Arrays don't have keys and only object So here is the code that worked for me.
const skids = JSON.parse(JSON.stringify(await skidTask.getSkidsForProcessingInvoice()));
let data = {}
skids.forEach(element => {
if(!rows[element.companyName]){
rows[element.companyName]=[];
}
rows[element.companyName].push(element);
});
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
This is my data,
"time" is number
[
{
"time": 202007150800,
"count": 10
},
{
"time": 202007160700,
"count": 11
},
{
"time": 202007160900,
"count": 12
}
]
How do I use "time" group data from 8 o'clock yesterday to 8 o'clock today and sum "count"
,For example, 7/15 data is 7/15 08:00 - 7/16 07:00
like this:
[
{
"time": 20200715,
"count": 21
},
{
"time": 20200716,
"count": 12
}
]
Try this function
function mapData(data) {
let result = [];
data.forEach(element => {
let t = element.time + 9200;
let substr = t.toString().substr(0, 8);
if(!result[substr])
result[substr] = 0;
result[substr] += element.count;
});
let returnResult = [];
result.forEach((element, index) =>
returnResult.push({
time: index,
count: element
})
);
return returnResult;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I can ordering a-z using the .sort() method in javascript, but I would get a JSON like this: (With a "A-Z" index containing the result)
data: {
"A": [
{
"name": "Anh Tuan Nguyen",
"age": 28
},
{
"name": "An Nguyen",
"age": 20
},
],
"Z": [
{
"name": "Zue Dang",
"age": 22
},
{
"name": "Zoom Jane",
"age": 30
},
]
}
var names = [{name:"a1"},{name:"a2"},{name:"b1"},{name:"b2"}.....];
var data = {};
for (var i = 0; i < names.length; i++) {
var n = names[i].name.subStr(0,1);
if (data[n] == null)
data[n] = [];
data[n].push(names[i]);
}
There is no way to sort a JSON data structure, however, we can do it by using the following process:
Get your data keys with Object.keys(myResults.data)
Sort you keys
Create a reduce function to transform your ordered keys into an ordered object
The snippet is here, I hope it helps:
var myResults = {
data: {
C: [
{
"name": "Kevin Doe",
"age": 22
}
],
A: [
{
"name": "Alex Doe",
"age": 31,
}
],
B: [
{
"name": "Boris Doe",
"age": 22
},
{
"name": "Birdo Doe",
"age": 30
},
]
}
};
var originalData = myResults.data;
// 1. get the keys
var dataKeys = Object.keys(originalData);
// 2. sort the keys
var sortedKeys = dataKeys.sort();
// 3. create the object again
var orderedData = sortedKeys.reduce(function(result, key) {
return Object.assign(
{},
result,
{ [key]: myResults.data[key] }
);
}, {});
document.getElementById('original').innerHTML = JSON.stringify(originalData);
document.getElementById('sorted').innerHTML = JSON.stringify(orderedData);
h3 {
margin: 0;
}
code {
display: block;
margin-bottom: 15px;
padding: 10px;
background-color: #f9f9f9;
}
<h3>Original Data</h3>
<code id="original"></code>
<h3>Ordered Data</h3>
<code id="sorted"></code>
JavaScript objects are not ordered. If you want to iterate over an object's properties, you can sort the keys and then retrieve your values:
const result = {
data: {
Z: [],
F: [],
A: [],
D: []
}
};
Object
.keys(result.data)
.sort()
.map(key => console.log(key, result.data[key]));
UPDATE:
Exist a JavaScript library that make It possible: Lodash Utilities (https://lodash.com/docs/4.17.4). Contain methods for .sort() JSON (no Arrays) and a method to obtain the JSON for I asked in this question. I only did this:
//First, order my JSON alphabetically with _.sortBy method (I can even order by a nested property in my JSON)
var order = _.sortBy(require('./names'), function (el) { return el.name });
//Second, I group my order result by the first letter of my property 'name' in my JSON
var list = _.groupBy(order, (b) => b.name[0].toUpperCase());
This is my input:
[
{"name":"Mark"},
{"name":"Jul"},
{"name":"Alicia"},
]
This is my output:
[
"A": [
{
"name": "Alicia"
}
],
"J": [
{
"name": "Jul"
},
],
"M": [
{
"name": "Mark"
},
]
I hope this help to somebody!
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I've below JSON, am facing difficulty to get the key and value dynamically from JSON array:
var productJSON = {
"byProduct": {
"category": {
"Entertainment": {
"TV": 7,
"Speaker": 24,
"DVD Player": 5,
"Home Theater": 4
},
"Home": {
"Sofa Couch": 1,
"TV Furniture": 4
},
"Mobile": {
"iPhone 5s": 1,
"Accessories": 4
}
}
}
}
I'm want key, value from each category and put in two different array, one for product name and another for product count like:
["TV", "Speaker", "DVD Player", "Home Theater","Sofa Couch", "TV Furniture", "iPhone 5s", "Accessories"]
[7, 24, 5, 4,1,4,1,4]
Can someone help how can I get the output like this?
How can I get these value from above JSON array, below is my code but not able to parse all the item from each category:
var ProductJSON = productJSON.byProduct;
var productsName = [], productCount = [];
Object.keys(ProductJSON.category).forEach(function (v) {
var k = Object.keys(ProductJSON.category[v])[0];
productsName.push(k);
productCount.push(ProductJSON.category[v][k]);
});
console.log(productsName);
console.log(productCount);
Thanks for your help in advance.
Here is the complete solution in this fiddle.
var Products = productJSON.byProduct.category;
var productsName = [], productCount = [];
for (var product in Products) {
var items = Products[product]
for (var item in items) {
productsName.push(item);
productCount.push(items[item]);
}
}
console.log(productsName);
console.log(productCount);
This is in plain JavaScript.
You can do something like this using lodash forEach:
var productJSON = {"byProduct": {"category": {"Entertainment": {"TV": 7,"Speaker": 24,"DVD Player": 5,"Home Theater": 4},"Home": {"Sofa Couch": 1,"TV Furniture": 4},"Mobile": {"iPhone 5s": 1,"Accessories": 4}}}};
var Products = productJSON.byProduct.category;
var productsName = [],
productCount = [];
_.forEach(Products, function(items) {
_.forEach(items, function(v, k) {
productsName.push(k);
productCount.push(v);
});
});
console.log('productsName: ', productsName);
console.log('productCount: ', productCount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>