Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Sorry if this is a bit confusing, but I have this array:
[
{
name: 'id',
type: 'string',
primary: true
},
{
name: 'notes',
type: 'text',
default: '[]'
},
{
name: 'reminders',
type: 'text',
default: '[]'
}
]
How would I turn it into
{
notes: '[]',
reminders: '[]'
}
? Here's the logic: Any index with a default property, set the key in the new object to the index's name, and set the value to the index's default.
You can make it with reduce
var array = [
{
name: 'id',
type: 'string',
primary: true
},
{
name: 'notes',
type: 'text',
default: '[]'
},
{
name: 'reminders',
type: 'text',
default: '[]'
}
]
var result = array.reduce((prev, el) => {
if (el.default) {
prev[el.name] = el.default
}
return prev;
},{})
console.log(result);
You can use filter with Object.keys().
// Your initial array
const initialArray = [{
name: 'id',
type: 'string',
primary: true
},
{
name: 'notes',
type: 'text',
default: '[]'
},
{
name: 'reminders',
type: 'text',
default: '[]'
}
];
// Array just with items that haves a default value
const itensWithDefaultValue = initialArray.filter(item => Object.keys(item).includes('default'));
// Object to save items
let objectWithValues = {};
// Save items in object with name and you default value
itensWithDefaultValue.map(item => objectWithValues[item.name] = item.default);
console.log(objectWithValues);
Hope this helps!
const data = [
{
name: 'id',
type: 'string',
primary: true
},
{
name: 'notes',
type: 'text',
default: '[]'
},
{
name: 'reminders',
type: 'text',
default: '[]'
}
];
const result = Object.fromEntries(
data
.filter(it => "default" in it)
.map(it => ([it.name, it.default]))
);
console.log(result);
Use reduce:
const arr = [{
name: 'id',
type: 'string',
primary: true
},
{
name: 'notes',
type: 'text',
default: '[]'
},
{
name: 'reminders',
type: 'text',
default: '[]'
}
];
const obj = arr.reduce((acc, curr) => curr.default ? { ...acc,
[curr.name]: curr.default
} : acc);
console.log(obj);
You could spread new objects into a single object.
var data = [{ name: 'id', type: 'string', primary: true }, { name: 'notes', type: 'text', default: '[]' }, { name: 'reminders', type: 'text', default: '[]' }],
result = Object.assign({}, ...data.map(({ name, default: d }) => d && { [name]: d }));
console.log(result);
Related
Why 1st iteration data is getting replaced in 2nd iteration?
Is there any other simpler method in ES6 to achieve this?
a = [
{ name: 'NameOne', weekName: 'WeekOne' },
{ name: 'NameTwo', weekName: 'WeekTwo' },
];
b = [
{ id: 'Name', type: 'text', data: '' },
{ id: 'Week', type: 'text', data: '' },
];
c = [];
showOutput() {
this.a.forEach((element) => {
this.b.map((item) => {
if (item.id == 'Name') {
item.data = element.name;
}
if (item.id == 'Week') {
item.data = element.weekName;
}
this.c.push(item);
console.log('c', this.c);
});
});
}
Current Output :
[{ id: 'Name', type: 'text', data: 'NameTwo' },
{ id: 'Week', type: 'text', data: 'WeekTwo' },
{ id: 'Name', type: 'text', data: 'NameTwo' },
{ id: 'Week', type: 'text', data: 'WeekTwo' }]
Desired Output:
[{ id: 'Name', type: 'text', data: 'NameOne' },
{ id: 'Week', type: 'text', data: 'WeekOne' },
{ id: 'Name', type: 'text', data: 'NameTwo' },
{ id: 'Week', type: 'text', data: 'WeekTwo' }]
Problem with your code is that this.c.push(item); here the same object is getting referenced so in 2nd iteration it's changing the data that modified by 1st iteration. In order to solve this, you will have to clone the object (dereference somehow)
I have used c.push(Object.assign({}, item)); or you can use c.push(JSON.parse(JSON.stringify(item))); or any other way to clone the object before pushing into array (c in your case)
Note: This is just to point out the root cause of the issue, and it may not be the perfect solution for your scenario.
e.g.
a = [
{ name: 'NameOne', weekName: 'WeekOne' },
{ name: 'NameTwo', weekName: 'WeekTwo' },
];
b = [
{ id: 'Name', type: 'text', data: '' },
{ id: 'Week', type: 'text', data: '' },
];
c = [];
function showOutput() {
a.forEach((element) => {
b.map((item) => {
if (item.id == 'Name') {
item.data = element.name;
}
if (item.id == 'Week') {
item.data = element.weekName;
}
c.push(Object.assign({}, item)); // clone object
});
});
}
showOutput();
console.log('c', c);
For more information: https://javascript.info/object-copy
I am trying to loop through a nested object that looks like this:
let obj = {
cols: [
{ name: 'name', type: 'String' },
{ name: 'dob', type: 'Number' },
{ name: 'address', type: 'String' },
{ name: 'income', type: 'String' },
{ name: 'vehicleNumber', type: 'Number' },
{ name: 'assets', type: 'Number' }
],
row: [
{
name: 'randomInfo',
columns: ['name', 'address', 'assets'],
}
]
}
I am using the logic below to loop through the object's arrays, compare if they are equal, and if they are, I am returning them in an array. I am trying to return the entire object inside the cols key though. For e.g, if there are matching elements inside cols array' name value with the row array's columns key's value, (cols.name === row.columns[element], if there is a match return cols object)
//loop through the obj and get the keys before this
let cols = cols.map(col => col.name);
let row = row.map(ind => ind.columns);
let rowNamesFlattened = [].concat.apply([], row);
let matchingCols = cols.filter(element => row.includes(element));
The matchingCols object now has the matching names, but I want to ultimately return their type as well. Any idea how this can be done?
you can use filter directly on the cols array. However here I assumed that row array has only 1 element
let obj = {
cols: [
{ name: 'name', type: 'String' },
{ name: 'dob', type: 'Number' },
{ name: 'address', type: 'String' },
{ name: 'income', type: 'String' },
{ name: 'vehicleNumber', type: 'Number' },
{ name: 'assets', type: 'Number' }
],
row: [
{
name: 'randomInfo',
columns: ['name', 'address', 'assets'],
}
]
}
let matchingCols = obj.cols.filter(({name}) => obj.row[0].columns.includes(name))
console.log(matchingCols)
In case multiple elements present inside row array. can use flatMap to get flattened list of columns and then the same procedure as above
let obj = {
cols: [
{ name: 'name', type: 'String' },
{ name: 'dob', type: 'Number' },
{ name: 'address', type: 'String' },
{ name: 'income', type: 'String' },
{ name: 'vehicleNumber', type: 'Number' },
{ name: 'assets', type: 'Number' }
],
row: [
{
name: 'randomInfo',
columns: ['name', 'address', 'assets'],
},
{
name: 'randomInfo2',
columns: ['dob','name'],
}
]
}
let filtered = obj.cols.filter(({name}) => obj.row.flatMap(ind => ind.columns).includes(name))
console.log(filtered)
Another solution to get both matched and unmatched in one go using reduce. so no need 2 filter calls. referenced this
let obj = {
cols: [
{ name: 'name', type: 'String' },
{ name: 'dob', type: 'Number' },
{ name: 'address', type: 'String' },
{ name: 'income', type: 'String' },
{ name: 'vehicleNumber', type: 'Number' },
{ name: 'assets', type: 'Number' }
],
row: [
{
name: 'randomInfo',
columns: ['name', 'address', 'assets'],
},
{
name: 'randomInfo2',
columns: ['dob','name'],
}
]
}
let flatted = obj.row.flatMap(ind => ind.columns);
const result = obj.cols.reduce((acc, curr) => {
acc[flatted.includes(curr.name) ? 'match' : 'unmatch'].push(curr);
return acc;
}, { match: [], unmatch: [] });
console.log(result)
I want to combine two schemas in realm db and perform operations on them, just like join in sql. But i don't know how to do it. I did not
List item
understand anything from the document. How can I do that?I have two schematics
const barkod = {
name: 'barkod',
properties: {
StokNo: { type: 'int', indexed: true },
Barkod: { type: 'string', indexed: true },
Birim: 'string',
BarkodTipi: 'string',
Aciklama: 'string?',
YStokNo: 'int'
}
// primaryKey: 'Barkod',
}
const stok = {
name: 'stok',
primaryKey: 'StokNo',
properties: {
StokNo: 'int',
StokAdi: { type: 'string', indexed: true },
StokKisaAdi: 'string',
StokKodu: 'string',
StokTanimi: 'string',
GrupKodu: 'string',
KdvOranP: { type: 'int', default: 0 },
KDVOranT: { type: 'int', default: 0 },
OzelKodu1: 'string',
OzelKodu2: 'string',
OzelKodu3: 'string'
}
}`enter code here`
and I want to join these two schemas
'SELECT Stok.StokAdi, Barkod, StokNo FROM ? AS Barkod JOIN ? AS Stok ON Barkod.StokNo = Stok.StokNo',
I found the solution to the problem. And this is how I did it. Hope it helps for those who have this problem.
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
},
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
birthday: 'date',
cars: 'Car[]',
// picture: 'data?' // optional property
},
};
const exp1 = () => {
var person;
Realm.open({schema: [CarSchema, PersonSchema]})
.then(realm => {
realm.write(() => {
person = realm.create('Person', {
name: 'ayşegül',
birthday: new Date(1995, 11, 25),
// cars: 'Car[]',
});
console.log(person.cars);
let carList = person.cars;
carList.push({make: 'Honda', model: 'model1', miles: 100});
carList.push({make: 'Toyota', model: 'model2', miles: 200});
console.log(person);
});
})
.catch(error => {
console.log(error);
});
};
I have array of objects and it needs to return array of sum. if className.value identical then add Area.value values otherwise just return single value,
var obj = [{
Area: {
type: 'double',
value: 150
},
className: {
type: 'string',
value: "gold"
}
},
{
Area: {
type: 'double',
value: 130
},
className: {
type: 'string',
value: "silver"
}
},
{
Area: {
type: 'double',
value: 250
},
className: {
type: 'string',
value: "gold"
}
},
];
console.log(obj)
//expecting this array to return
console.log([400,130])
You can perform a reduce operation on the array, summing elements with the same className.value with an object.
var obj = [{ Area: { type: 'double', value: 150 }, className: { type: 'string', value: "gold" } }, { Area: { type: 'double', value: 130 }, className: { type: 'string', value: "silver" } }, { Area: { type: 'double', value: 250 }, className: { type: 'string', value: "gold" } }, ];
const res = Object.values(
obj.reduce((acc,curr)=>{
acc[curr.className.value] = (acc[curr.className.value] || 0) + curr.Area.value;
return acc;
}, {})
);
console.log(res);
Effectively just loop through the object and account for undefined. Use the className.value as element name to avoid duplicates.
function calculateValues(obj) {
var output = [];
for (var key in obj) {
output[obj[key].className.value] = (obj[key].className.value in output ? output[obj[key].className.value] : 0) + obj[key].Area.value;
}
return output;
}
console.log(calculateValues(obj));
Use Array#reduce to sum up the values for the different classes. For this look with Object#hasOwnProperty if there is in the accumulator an property with the classname of the current object. If not so, so add one with this name (e.g. "gold") and add the value from the current object to this. Otherwise add to this property the value directly.
After the summation to this object with reduce I get with Object#values the values from the Object as an array. At the end I just have to look if the array has only 1 entry. If so then return it as value otherwise return the array.
function makeSum(arr) {
let result = Object.values(arr.reduce((acc, cur) => {
let classVal = cur.className.value;
if (!acc.hasOwnProperty(classVal)) {
acc[classVal] = cur.Area.value;
} else {
acc[classVal] += cur.Area.value;
}
return acc;
},{}));
if (result.length===1) result = result[0];
return result;
}
let arr = [{ Area: { type: 'double', value: 150 }, className: { type: 'string', value: "gold" } }, { Area: { type: 'double', value: 130 }, className: { type: 'string', value: "silver" } }, { Area: { type: 'double', value: 250 }, className: { type: 'string', value: "gold" } }, ];
console.log(makeSum(arr));
This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed 3 years ago.
I want to modify the data that API provides to client. I can only retrieve the unique category value using Set. Then I'm stuck how to proceed further.
const serverData = [
{
category: 'address',
label: 'Street',
type: 'text'
},
{
category: 'address',
label: 'Country',
type: 'text'
},
{
category: 'person',
label: 'FirstName',
type: 'text'
},
{
category: 'person',
label: 'LastName',
type: 'text'
}
];
I want the above to be modified like below. There can be many categories
const modifiedData = {
address : [
{
label: 'Street',
type: 'text'
},
{
label: 'Country',
type: 'text'
},
],
person : [
{
label: 'FirstName',
type: 'text'
},
{
label: 'LastName',
type: 'text'
}
]
};
Please help me achieve this. Thanks in advance!
You could use the reduce function to format your data. Here is an example:
const serverData = [
{
category: 'address',
label: 'Street',
type: 'text'
}, {
category: 'address',
label: 'Country',
type: 'text'
}, {
category: 'person',
label: 'FirstName',
type: 'text'
}, {
category: 'person',
label: 'LastName',
type: 'text'
}
];
const formatData = data => {
return data.reduce((result, item) => ({
...result,
[item.category] : [
...(result[item.category] || []),
item
]
}), {});
}
console.log(formatData(serverData));