Convert String into Array in Javascript Angular 6 - javascript

I have a dynamically generated Array that is shown from console.log(temp):
[{user_id: "test#random.com", status: "Idle"}],
[{user_id: "whatever#random.com", status: "Busy"}]
My code:
this.scheduleService.getShiftSchedule().subscribe((temp)=>{
this.api = temp;
console.log(temp);
})
How do I change the format of my Array to become like the Array below?
[[{id: 1,content: 'test#random.com'},{id: 2,content: 'Idle'}],
[{id: 1,content: 'whatever#random.com'},{id: 2,content: 'Busy'}]]

You could map the objects by taking an array of the wanted keys and their id.
var data = [{ user_id: "test#random.com", status: "Idle" }, { user_id: "whatever#random.com", status: "Busy" }],
ids = [['user_id', 1], ['status', 2]],
result = data.map(o => ids.map(([key, id]) => ({ id, content: o[key] })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

var array = JSON.parse("[" + string + "]");

var arr = [1,2,3,4,5,6,7,8,9]
var newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr)
you may try like this

Related

how to add key of object in array?

Guys.
I have array like this
array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]
And I want to edit this array to
array = [ "A":{name:"A",data:"..."},"B":{name:"B",data:"..."},"C":{name:"C",data:"..."}
How could I set object key from its own value?
For getting an object, you could take Object.fromEntries with the mapped key/value pairs
var array = [{ name: "A", data: "..." }, { name: "B", data: "..." }, { name: "C", data: "..." }],
result = Object.fromEntries(array.map(o => [o.name, o ]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this:
console.log(array.map(el => ({[el.name]: el})));
JavaScript array doesn't work that way. An array's index value can only have an increasing numeric indexes([0, 1, ..., n]). If you wan't to create such list you can create the object instead of an array.
const array = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}];
const newList = {};
array.forEach(obj => {
newList[obj.name] = obj;
});
console.log({ newList });
In this way you can create the object out of array. You can then loop the object's keys like in arrray using:
Object.keys(newList).forEach((key) => {
console.log(newList[key]);
})
. Hope it helps.
Just do this.
var arr = [{name:"A",data:"..."},{name:"B",data:"..."},{name:"C",data:"..."}]
var output = arr.map(elem => ({[elem.name]: elem}))
console.log(output)

Rearrange dynamic Object to form a structured Object

I have an Object like this:
const val = {"abc":{"1":1, "2":6,"3":5},"def":{"1":3, "2":4,"3":8},"xyz":{"1":5, "2":6,"3":7}}
I want to transform the object data like below:
[{"abc":1,"def":3,"xyz":5},{"abc":6,"def":4,"xyz":6}, ...]
All the values are dynamic, any number of inner object may be there
I have tried like this:
const val = {"abc":{"1":1, "2":6,"3":5},"def":{"1":3, "2":4,"3":8},"xyz":{"1":5, "2":6,"3":7}}
let dataObj = {};
let secondArr = [];
let dataArr =[]
Object.entries(val).map(firstObj=>{
Object.entries(firstObj[1]).forEach(secondObj => {
dataObj={[firstObj[0]]:secondObj[1]};
secondArr.push(dataObj);
})
dataArr.push(secondArr)
})
console.log(dataArr)
Can anyone tell me a solution for this?
Thanks in advance
You could iterate the entries of the objects and take the inner keys as indices of the array with new objects with outer key and value.
var data = { abc: { 1: 1, 2: 6, 3: 5 }, def: { 1: 3, 2: 4, 3: 8 }, xyz: { 1: 5, 2: 6, 3: 7 } },
result = Object
.entries(data)
.reduce((r, [k, o]) => {
Object.entries(o).forEach(([i, v]) =>
Object.assign(r[i - 1] = r[i - 1] || {}, { [k]: v }));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Javascript update Object attribute value

I´m trying to update the object atribute:
data : [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
]
new object would be updated as below.
NewData: [
{"id":1,"rp":"2426","cr":"11/11"},
{"id":1,"rp":"1119","cr":"19/21"},
{"id":1,"rp":"3453","cr":"23/81"}
]
I looking to update the object cr atribute for all values, for example using javascript.replace() method, I would do replace("-","/").
That's just a simple usage of Array#map and String#replace:
ES2018
const data = [{"id":1,"rp":"2426","cr":"11-11"},{"id":1,"rp":"1119","cr":"19-21"},{"id":1,"rp":"3453","cr":"23-81"}]
const r = data.map(({ cr, ...rest }) => ({ cr: cr.replace('-', '/'), ...rest }));
console.log(r);
You could use map method to create new array and replace to update cr property.
var data = [{"id":1,"rp":"2426","cr":"11-11"},{"id":1,"rp":"1119","cr":"19-21"},{"id":1,"rp":"3453","cr":"23-81"}]
var update = data.map(({cr, ...rest}) => ({...rest, cr: cr.replace("-","/")}))
console.log(update)
You could iterate and map the array.
var data = [{ id: 1, rp: "2426", cr: "11-11" }, { id: 1, rp: "1119", cr: "19-21" }, { id: 1, rp: "3453", cr: "23-81" }],
newArray = data.map(o => Object.assign({}, o, { cr: o.cr.replace("-","/") }));
console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can try this
let data = [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
];
let newData = data.map(e=>{
e.cr = e.cr.replace(/-/, '/')
return e
})
console.log(newData)
Just try below
data.forEach(function(object){
object["cr"] = object["cr"].replace("-","/");
});
Try this:
const data = [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
];
const newData = data.map(item => ({...item, cr: item.cr.replace(/-/g, '/')}));
console.log(newData);
If you need it to work in IE11:
const data = [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
];
const newData = data.map(
function(item) {
return {
id: item.id,
rp: item.rp,
cr: item.cr.replace(/-/g, '/')
}
}
);
console.log(newData);
const data = [{"id":1,"rp":"2426","cr":"11-11"},{"id":1,"rp":"1119","cr":"19-21"},{"id":1,"rp":"3453","cr":"23-81"}]
const r = JSON.parse(JSON.stringify(data).replace(/-/g,'/'))
console.log(r);

Reduce JavaScript Objects into Array of Formatted Objects

I have an array of objects in the format
{type: number, sub_type: number}
I need to sort them into an array of objects formatted like this
{
type_id: (type from at least one object in array above),
sub_types: [
(all sub types from objects in array above that match this type)
]
}
This is what I came up but I think there is a more efficient way. rawTypes is an array of objects in need of formatting, types ends up being the array of formatted objects.
const typeIds = [...new Set(rawTypes.map(val => val.type))];
const types = typeIds.map(val => ({type_id: val, sub_types: [] }));
rawTypes.forEach(obj => {
let typeIndex = types.reduce((accum, val, i) => val.type_id === obj.type ? i : accum, 0);
types[typeIndex].sub_types.push(obj.sub_type);
});
I think a better solution would use recursion but I can't think of how to do it.
Look at this approach
var data = [{type: 5, sub_type: 10}, {type: 5, sub_type: 11}, {type: 6, sub_type: 12}];
var obj = data.reduce((a, c) => {
var current = a[`type_id_${c.type}`];
if (current) {
current.sub_types.push(c.sub_type);
} else {
var key = `type_id_${c.type}`;
a = { ...a, ...{ [key]: {sub_types: [c.sub_type], 'key': c.type} } };
}
return a;
}, {});
var array = Object.keys(obj).map((k) => ({ 'type': obj[k].key, 'subtypes': obj[k].sub_types }));
console.log(array)
.as-console-wrapper {
max-height: 100% !important
}

add array to object which is inside array of objects if second array of object has same value

So if I have two array with same key and value:
var firstArr = [{name:'Lorem', post_id:2},{name:'Ipsum', post_id:1}];
var secondArr = [{sec:'Deca', another_id:2},{sec:'Meca', another_id:1},{sec:'Raca', another_id:2}];
What i want to achieve is when:
firstArr.map(function(item,i) {
if(item.post_id === secondArr[i].another_id) {
item.randKey = secondArr[i]
}
});
But the output of this is wrong
result is
firstArr[0];
Object {name: "Lorem", post_id: 2, randKey: Array(1)}
What i want to achieve is that
firstArr[0];
Object {name: "Lorem", post_id: 2, randKey: Array(2) = {sec:'Deca', another_id:2},{sec:'Raca', another_id:2} }
So my question is it only appends one array, but it should append both if (post_id =2 === another_id = 2)
I am hoping i was clear enough.
Try with Array#forEach for iterate the firstArray and Array#filter used for filter the secondArr with respected postid match
var firstArr = [{name:'Lorem', post_id:2},{name:'Ipsum', post_id:1}];
var secondArr = [{sec:'Deca', another_id:2},{sec:'Meca', another_id:1},{sec:'Raca', another_id:2}];
firstArr.forEach(function(item,i) {
item.randKey = secondArr.filter(a=> a.another_id == item.post_id)
});
console.log(firstArr)
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use a temporary object for collecting all items of secondArr with the same another_id. Then iterate firstArr and assign the collected items.
var firstArr = [{ name: 'Lorem', post_id: 2 }, { name: 'Ipsum', post_id: 1 }],
secondArr = [{ sec: 'Deca', another_id: 2 }, { sec: 'Meca', another_id: 1 }, { sec: 'Raca', another_id: 2 }],
temp = {};
secondArr.forEach(function (a) {
temp[a.another_id] = temp[a.another_id] || [];
temp[a.another_id].push(a);
});
firstArr.forEach(function (a) {
a.randKey = temp[a.post_id];
});
console.log(firstArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources