Learning JavaScript. I need to plot some data (I'm using Nivo).
I have data from my API in the format of:
[{"as_at_date":"2020-02-21","value":815202269.5,"num":139},{"as_at_date":"2020-02-25","value":809209302.32,"num":139},{"as_at_date":"2020-03-12","value":723686212.35,"num":139},{"as_at_date":"2020-03-13","value":734798809.24,"num":139},{"as_at_date":"2020-03-16","value":701366943.2,"num":139},{"as_at_date":"2020-03-17","value":710833514.89,"num":139},{"as_at_date":"2020-03-18","value":699154469.83,"num":139},{"as_at_date":"2020-03-19","value":694649684.34,"num":139},{"as_at_date":"2020-03-20","value":685400033.9,"num":139}]
To plot a line chart with Nivo I need to alter the above array into:
[{"id": 'XXXXX",
"data": [{"x":"2020-02-21","y":815202269.5},{"x":"2020-02-25","y":809209302.32},{"x":"2020-03-12","y":723686212.35},{"x":"2020-03-13","y":734798809.24},{"x":"2020-03-16","y":701366943.2},{"x":"2020-03-17","y":710833514.89},{"x":"2020-03-18","y":699154469.83},{"x":"2020-03-19","y":694649684.34},{"x":"2020-03-20","y":685400033.9}]
Ignore "num" property.
nest the data and create an "id"
Change as_at_date to "x", value to "y"
Last attempt was trying to use .map like .map(item => [{"x": item['as_at_date']}, {"y": item['value']}]) but wasn't quite right.
Appreciate any help, thanks!
I would use .reduce() to create the nested data first. Then adding id and data properties to the final object.
Try the following:
const data = [{"as_at_date":"2020-02-21","value":815202269.5,"num":139},{"as_at_date":"2020-02-25","value":809209302.32,"num":139},{"as_at_date":"2020-03-12","value":723686212.35,"num":139},{"as_at_date":"2020-03-13","value":734798809.24,"num":139},{"as_at_date":"2020-03-16","value":701366943.2,"num":139},{"as_at_date":"2020-03-17","value":710833514.89,"num":139},{"as_at_date":"2020-03-18","value":699154469.83,"num":139},{"as_at_date":"2020-03-19","value":694649684.34,"num":139},{"as_at_date":"2020-03-20","value":685400033.9,"num":139}];
const nested = data.reduce((a, c) => a.concat({x: c['as_at_date'], y: c['value']}), []);
const result = {
id: 'XXXXX',
data: nested
};
console.log(result);
I hope this helps!
map is certainly the way to go.
Here's my approach:
const data = [{"as_at_date":"2020-02-21","value":815202269.5,"num":139},{"as_at_date":"2020-02-25","value":809209302.32,"num":139},{"as_at_date":"2020-03-12","value":723686212.35,"num":139},{"as_at_date":"2020-03-13","value":734798809.24,"num":139},{"as_at_date":"2020-03-16","value":701366943.2,"num":139},{"as_at_date":"2020-03-17","value":710833514.89,"num":139},{"as_at_date":"2020-03-18","value":699154469.83,"num":139},{"as_at_date":"2020-03-19","value":694649684.34,"num":139},{"as_at_date":"2020-03-20","value":685400033.9,"num":139}];
function reformattedData(arr) {
// Destructure only the required properties
return arr.map(({ as_at_date, value }) => {
// And just return those values in a new object
// using the new property names
return { x: as_at_date, y: value };
});
}
const out = { id: 'xxx', data: reformattedData(data) };
console.log(out);
Your attempt was almost correct, just omit the surrounding []:
const input = [{"as_at_date":"2020-02-21","value":815202269.5,"num":139},{"as_at_date":"2020-02-25","value":809209302.32,"num":139},{"as_at_date":"2020-03-12","value":723686212.35,"num":139},{"as_at_date":"2020-03-13","value":734798809.24,"num":139},{"as_at_date":"2020-03-16","value":701366943.2,"num":139},{"as_at_date":"2020-03-17","value":710833514.89,"num":139},{"as_at_date":"2020-03-18","value":699154469.83,"num":139},{"as_at_date":"2020-03-19","value":694649684.34,"num":139},{"as_at_date":"2020-03-20","value":685400033.9,"num":139}];
const outputData = input.map(item => ({ x: item.as_at_date, y: item.value }));
console.log(outputData);
const result = {
id: 'XXXX', // create your id here,
data: outputData,
};
console.log(result);
You can try this one
const array = [{"as_at_date":"2020-02-21","value":815202269.5,"num":139},{"as_at_date":"2020-02-25","value":809209302.32,"num":139},{"as_at_date":"2020-03-12","value":723686212.35,"num":139},{"as_at_date":"2020-03-13","value":734798809.24,"num":139},{"as_at_date":"2020-03-16","value":701366943.2,"num":139},{"as_at_date":"2020-03-17","value":710833514.89,"num":139},{"as_at_date":"2020-03-18","value":699154469.83,"num":139},{"as_at_date":"2020-03-19","value":694649684.34,"num":139},{"as_at_date":"2020-03-20","value":685400033.9,"num":139}];
const formatted_array = input.map((item) => {
return {x: item.as_at_date, y: item.value}});
const final_data = {
id: 'XXXX',
data: formatted_array ,
};
console.log(final_data);
In my post request I need to pass an array with an object inside it.
when I tried to add new properties inside an object its adding.
but when I tried to add when an object is present inside an array its not adding.
I have sportsvalues as array const sportsValues = [{ ...values }];
I am trying to build something like this, so that I can pass in the api
[
{
"playerName": 3,
"playerHeight": 1
}
]
can you tell me how to fix it.
providing my code snippet below.
export function sports(values) {
const sportsValues = [{ ...values }];
sportsValues.push(playerName:'3');
console.log("sportsValues--->", sportsValues);
// sportsValues.playerName = 3//'';
// sportsValues.playerHeight = 1//'';
console.log("after addition sportsValues--->", sportsValues);
console.log("after deletion sportsValues--->", sportsValues);
return dispatch => {
axios
.post(`${url}/sport`, sportsValues)
.then(() => {
return;
})
.catch(error => {
alert(`Error\n${error}`);
});
};
}
Since sportsValues is an array of objects, you can push new object into it. Check out code below.
const sportsValues = [];
sportsValues.push({
playerName:'3',
playerHeight: 1,
});
console.log(sportsValues);
I don't fully understand what you're trying to do, but here's some pointers:
If you're trying to update the object that's inside the array, you first have to select the object inside the array, then update it's attribute:
sportsValues[0].playerName = 3
although, I recommend building the object correctly first, then passing it to the array, it makes it a little easier to understand in my opinion:
const sportsValues = [];
const firstValue = { ...values };
firstValue.playerName = '3';
sportsValues.push(firstValue);
or
const firstValue = { ...values };
firstValue.playerName = '3';
const sportsValues = [firstValue];
or
const sportsValues = [{
...values,
playername: '3',
}];
if you're trying to add a new object to the array, you can do this:
const sportsValues = [{ ...values }];
sportsValues.push({ playerName: '3' });
etc...
Array.push adds a new item to the array, so in your code, you're going to have 2 items because you assign 1 item at the beginning and then push a new item:
const ar = [];
// []
ar.push('item');
// ['item']
ar.push({ text: 'item 2' });
// ['item', { text: 'item 2' }]
etc...
export function sports(values) {
const sportsValues = [{ ...values }];
sportsValues.push(playerName:'3');
let playerName='3'
sportsValues.playerName= playerName; // you can bind in this way
console.log("sportsValues--->", sportsValues);
return dispatch => {
axios
.post(`${url}/sport`, sportsValues)
.then(() => {
return;
})
.catch(error => {
alert(`Error\n${error}`);
});
};
}
I am trying to filter data inside array object of array object, Please find below code for more information.
var data = [
{
name:'testdata1',
subdata:[{status:'fail'},{status:'success'}]
},
{
name:'testdata2',
subdata:[{status:'fail'},{status:'success'}]
}
]
Expected Data:
var successdata = [
{
name:'testdata1',
subdata:[status:'success'}]
},
{
name:'testdata2',
subdata:[status:'success'}]
}
];
var FailureData =[
{
name:'testdata1',
subdata:[{status:'fail'}]
},
{
name:'testdata2',
subdata:[{status:'fail'}]
}
];
I missed curly braces,So i am updating
Hope this helps.
const data = [{
name: 'testdata1', subdata: [{status: 'fail'}, {
status:
'success'
}]
},
{
name: 'testdata2', subdata:
[{status: 'success'}, {status: 'fail'}]
}
];
const filterData = (data, status) => data.reduce((acc, val) => {
const sub = val.subdata.map((v) => v.status === status ? ({ name: val.name, subdata: [v] }) : null).filter(f => f !== null);
return acc.concat(sub);
}, []);
const successData = filterData(data, 'success');
const failureData = filterData(data, 'fail');
console.log('successData', successData);
console.log('failureData', failureData);
You could map your arrays using Array.map():
var successData = data.map(item => ({name: item.name, subdata:[{status:'success'}]})
What I guess you want to do is filter the array based on subdata status.
I also guess that what subdata should have is just the status property and your code would be: var data = [{name:'testdata1',subdata:[{status:'fail'},{status:'success'}] }.
Then you want to look in the subdata array and find which data have success and failure in them.
So what you could be looking for is this:
var successData = data.filter(sdata => {
var successFlag=false;
sdata.subdata.forEach(subdata=>{
if (subdata.status==='success'){
successFlag = true;
}
}
return successFlag;
}
The same with the failureData.
For more information you could check the Array.prototype.filter function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
P.S. As mentioned in a comment to your question as well, your subdata array cannot be an object with two of the same property
var data = [{name:'testdata1',subdata:[{status:'fail'}, {status:'success'}] },{name:'testdata2',subdata:[{status:'success'}, {status:'fail'}] }]
var successData = filterByStatus('success', data);
var failureData = filterByStatus('fail', data);
function filterByStatus(status, data) {
return data.map(d => {
var newObj = Object.assign({}, d);
newObj.subdata = newObj.subdata.filter(s => s.status === status);
return newObj;
});
}
console.log('successData', successData);
console.log('failureData', failureData);
one of possible ways to do what you want if you have one success property in your object
I have an array of objects:
[{name:'john',age: 24}, {name:'arian', age: 34}]
I want to get the following array back:
[{title:'john'},{title:'arian'}]
The following code:
let tableData = {
header: [{title: 'name'}],
data: _.map(groups, group => {
return group.name
})
};
results in: ['john', 'arian']
but this code:
let tableData = {
header: [{title: 'name'}],
data: _.map(groups, group => {
return {title: group.name} // <-- this line changed
})
};
returns an array of length 0 for data. Why does this happen ? isn't it basically the same ?
Update 1
How I get groups:
const { groups } = this.props;
This is a react code.
The problem stated has a very simple solution. You are doing it right, but need little change in the code
var obj = [{name:'john',age: 24}, {name:'arian', age: 34}];
var result = _.map(obj,(value)=>{
return {name:value.name};
});
If you are expecting each member of your resultant array to be a object then you need to return that kind of object from your map, as simple as that. Either you use lodash or pure javascript version of map, answer is the same:
_.map(groups, o=>({'title': o.name}))
Or with native javascript Array map
groups.map(o=>({'title': o.name}))
Why not use native Array.prototype.map?
let data = [{name:'john',age: 24}, {name:'arian', age: 34}]
console.log(data.map( (item) => { return { title: item.name } }))
I have attributes of objects of an array that I would like to store in an array. Below is my data.
What I want to do achieve is to store displays name attribute in opt[] so it would look like this opt = ['info1', 'info2', 'info3', ... ]
getEditData (id) {
axios.get('/api/campaign/getEdit/' + id)
.then(response =>{
this.campaign = response.data.campaign;
})
.catch(e=>{
console.log(e.data);
this.error = e.data
})
}
Above snippet is the source of the campaign object
You can use this expression:
campaigns.displays.map( ({name}) => name );
const campaigns = { displays: [{ name: 'info1'}, { name: 'info2'}] };
const result = campaigns.displays.map( ({name}) => name );
console.log(result);
This will display an array containing the property names of each object in the displays array
var data = {
displays: [
{
capacity: 9000,
id: 1,
imei: 44596
}
]
};
data.displays.forEach(function(obj, idx) {
console.log(Object.keys(obj));
});
Object.keys() is what you need