Array Split Inside Objects - javascript

I have an object Regions{} which stores multiple objects, following code block showing countryName : [regions,..,..]
Regions = { Afghanistan:["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"]
Albania:["Berat~01", "Dibër~09", "Durrës~02",]
}
Which giving me result like this:
Afghanistan: Array(n)
0: "Badakhshan~BDS"
1: "Badghis~BDG"
what I am trying to achive is :
Afghanistan: Array(n)
0:{value: "Badakhshan", lable: "BDS"}
1:{value: "Badghis", lable: "BDG"}
thanks in advance
PS: for the sake of some ruthless fellows following is the code what I have tried yet
let countries = CountryRegionData
let regions = {}
countries = countries.map(country => {
regions = {
...regions,
[country[0]]: country[2].split('|')
}
return {
value: country[1],
label: country[0]
}
})
console.log("countries",countries)
console.log("regions",regions)
let values = regions["Afghanistan"];
values = values.map(value =>{
return {
value: value,
lable: value
}
})

You can use split and map, this code is changing values in original object, if you want to build a new object you can use reduce instead of forEach
let Regions = {
Afghanistan: ["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"],
Albania: ["Berat~01", "Dibër~09", "Durrës~02", ]
}
Object.entries(Regions).forEach(([key,value])=>{
Regions[key] = value.map(data=>{
let [value,label] = data.split('~')
return {value,label}
})
})
console.log(Regions)

Do something like:
Regions.map(region => region.map(txt => {
const [val, lbl] = txt.split("~");
return { value: val, lable: lbl};
}));

Messy but gets the work done. Using nested forEach loops
var Regions = {
Afghanistan: ["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"],
Albania: ["Berat~01", "Dibër~09", "Durrës~02", ]
}
var ar = [];
Object.keys(Regions).forEach(function(e) {
Regions[e].forEach(function(k) {
var arr = k.split('~');
ar.push({
value: arr[0],
label: arr[1]
})
})
Regions[e] = ar;
ar = [];
})
console.log(Regions)

Use the map function to iterate the object.
Regions = {
Afghanistan: ["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"],
Albania: ["Berat~01", "Dibër~09", "Durrës~02", ]
};
const finalObject = Object.keys(Regions).map(region => {
return {
[region]: Regions[region].map(country => {
const [value, lable] = country.split("~");
return {
value,
lable
};
})
};
});
console.log(finalObject);

Related

Map Data Object in JavaScript

I'm new to JavaScript, Don't mind asking for naïve question
I'm getting a response from API like the following format
const response = {
"slaTrend": {
"acheived": {
"01-01": 74.0740740741,
"01-02": 74.0740740741,
"01-03": 55.5555555556
},
"breached": {
"01-01": 636.6716854642,
"01-02": 636.5140839914,
"01-03": 477.4679362239
}
}
}
I need output like the following.
[{name: 'acheived', dates: ['01-01', '01-02', '01-03'], values: [74.0740740741, 74.0740740714, 74.0740740741]}, {name: 'breached', dates: ['01-01', '01-02', '01-03'], values: [636.6716854642, 636.514083991, 477.4679362239]}]
Can someone please help? Thank you in advance
You can achieve this with simple for...in loop. Try like this
const response = {
"slaTrend": {
"acheived": {
"01-01": 74.0740740741,
"01-02": 74.0740740741,
"01-03": 55.5555555556
},
"breached": {
"01-01": 636.6716854642,
"01-02": 636.5140839914,
"01-03": 477.4679362239
}
}
}
const output = []
for (const trend in response.slaTrend) {
const dates = [];
const values = [];
const slaTrend = response.slaTrend[trend] || {}
for (const date in slaTrend) {
dates.push(date)
values.push(slaTrend[date])
}
output.push({ name: trend, dates, values })
}
console.log(output)
const newData = [];
const baseObj = response["slaTrend"];
Object.keys(baseObj).forEach(function(key){
const dates = Object.keys(baseObj[key]);
const vals = Object.values(baseObj[key]);
newData.push({name: key, dates: dates, values: vals});
});
console.log('%j', newData);

Convert to Object and Adding property to object of array

I want to make filter by date with this object of array
const mapDateRange = () => {for (let elem in catchData) {
let x = {startDate:catchData[elem][0],finishDate:catchData[elem][1]};
return x;
}};
but its only catch one object of array
this is latest data has processing
const data = {
["01-08-2019", "08-08-2019"],
["08-08-2019", "15-08-2019"],
["15-08-2019", "22-08-2019"],
["22-08-2019", "29-08-2019"]
};
this is what i expected
const data = [
{
startDate:"01-08-2019", finisDate:"08-08-2019"
},
{
startDate:"08-08-2019", finisDate:"15-08-2019"
},
{
startDate:"15-08-2019", finisDate:"22-08-2019"
},
{
startDate:"22-08-2019", finisDate:"29-08-2019"
}
];
So there are a few problems in the code you wrote:
Your data started as an object ({}), but its built as an array, so I corrected that.
Your function mapDateRange uses catchData but it does not exist anywhere so I made the function except an argument, which will be the catchData.
Most important: You returned x which is only 1 item in the array of data. So I created an empty array and pushed x values to the array.
const data = [
["01-08-2019", "08-08-2019"],
["08-08-2019", "15-08-2019"],
["15-08-2019", "22-08-2019"],
["22-08-2019", "29-08-2019"]
];
const mapDateRange = (catchData) => {
let new_data = [];
for (let elem in catchData) {
let x = {
startDate: catchData[elem][0],
finishDate: catchData[elem][1]
};
new_data.push(x);
}
return new_data;
};
console.log(mapDateRange(data));
const data = [
["01-08-2019", "08-08-2019"],
["08-08-2019", "15-08-2019"],
["15-08-2019", "22-08-2019"],
["22-08-2019", "29-08-2019"]
];
const mapDataRange = (data) => {
const result = [];
data.forEach((item) => {
const x = { 'startDate': item[0], 'finishDate': item[1] };
result.push(x);
});
return result;
}
console.log(mapDatatRange(data));
In this way you will get your desire result by using map function
data = data.map((obj) => {
return {
startDate: obj[0],
finishDate: obj[1]
}
});
console.log(data)
try to do with .map and array destructuring with ES6 syntax
data.map(([ startDate, finishDate ]) => { startDate, finisDate })

need to pass an array with an object inside it

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}`);
});
};
}

Filter data inside array object of array object using javascript

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

How to turn this array into a JavaScript object?

The following code loops through a JavaScript object and collects only the properties that are arrays:
const building = this.building
let panoramaList = []
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList.push({ [key]: panoramas })
}
}
console.log(panoramaList)
In other words, it takes this:
{
name: '',
description: ''.
livingroom: Array[0],
study: Array[1],
bedroom: Array[0]
}
and turns it into this:
[
{ livingroom: Array[0] },
{ study: Array[1] },
{ bedroom: Array[0] }
]
However, what I need to produce is this:
{
livingroom: Array[0],
study: Array[1],
bedroom: Array[0]
}
How to accomplish that?
Change this :
const building = this.building
let panoramaList = []
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList.push({ [key]: panoramas })
}
}
console.log(panoramaList)
to this :
const building = this.building
let panoramaList = {}
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList[key]=panoramas
}
}
console.log(panoramaList)
Use Object.keys and try something like this:
var input = {} //...your input array
var keys = Object.keys(input);
var result = {};
keys.forEach(function (key) {
if (Array.isArray(input[key])) {
result[key] = input[key];
}
});
try this
var output = Object.keys(building).map(function(val){ return { val : building[val] } });
For the final output
var panoramaList = {}
Object.keys(building).forEach(function(val){
if ( Array.isArray(building[val] )
{
panoramaList[val] = building[val];
}
});
Make sure to define panoramaList as an object.
This works
var arrays = {
name: '',
description: '',
livingroom: ['1','www'],
study: ['2','sss'],
bedroom: ['3','aaa'],
Kitchen: ['4','bbb'],
}
const building = arrays
let panoramaList = {};
for (let key in building) {
const panoramas = building[key]
if (Array.isArray(panoramas)) {
panoramaList[key] = panoramas;
}
}
console.log(panoramaList);
https://jsbin.com/paqebupiva/1/edit?js,console,output
Rather than building a new object, you might just need to delete the unwanted properties from the object that you have:
var data = {
name: '',
description: '',
livingroom: [],
study: [1],
bedroom: [0]
};
Object.keys(data).forEach(function(key) {
if (!Array.isArray(data[key])) delete data[key];
})
document.write(JSON.stringify(data));

Categories