JS - Insert an object inside an object having a same data - javascript

I'm arranging series of data having a same data in it
var arr = [{id: 1, parent: "a"}, {id: 2, parent: "b"}];
var cArr = [
{parentID: 1, a1: "1"},
{parentID: 1, a1: "2"},
{parentID: 2, a1: "3"},
{parentID: 2, a1: "4"}
];
and I want to join them and will look like this
var array = [
{ id: 1, parent: "1", data: [{ a1: "1"}, { a1: "2"}] },
{ id: 2, parent: "2", data: [{ a1: "3"}, { a1: "4"}] }
];
How do I add variable like parent and data inside of object array?
How do I access id: 1, parent: "1", data: [{ a1: "1"}, { a1: "2"}]? Is it like array[0]?
I'm new to JS and like this if I have errors I'm so sorry. I'm using console.log() to check things up

You can achieve it like this:
var array = [{ parent: "1", data: [{ a1: "1"}, { a1: "2"}] },
{parent: "2", data: [{ a1: "3"}, { a1: "4"}]
}];
console.log(array[0].parent); // 1
console.log(array[0].data) // [{ a1: "1"}, { a1: "2"}]
To add an item just do like this using .push method
array.push({ parent: "3", data: [{ a1: "5"}, { a1: "6"}] });

Iterate the arr with Array.map(), and create a new object with the content of the original object using object spread. To get the respective items from cArr use Array.slice() with the index of the current item:
const arr = [{parent: "1"}, {parent: "2"}];
const cArr = [{a1: "1"}, {a1: "2"}, {a1: "3"}, {a1: "4"}];
const result = arr.map((o, i) => ({
...o, // copy the original object's content
data: cArr.slice(i * 2, i * 2 + 2) // slice the sub-array from cArr
}));
console.log(result);

Related

create and push key value object in array

I have an array :
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}]
I want to create a new array of objects where I have to give key and value in it.
For eg,:
const newArr = [{1,4},{2,1},{3,2}]
here first item of an object is the key, which has to increase as the number of objects increase, and second item is the value from data.
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}];
const out = data.map((item, index) => [index + 1, item.value]);
console.log(out);
I hope this is your solution:
const data = [
{
label: 'a',
value: '4'
},
{
label: 'b',
value: '1'
},
{
label: 'c',
value: '2'
},
]
const newArrOfObj = data.reduce((arr, current, index)=> [...arr, {[index+1]:current.value}], []);
console.log(newArrOfObj) //[ { 1: '4' }, { 2: '1' }, { 3: '2' } ]
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr.push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
index.js
let arr = [];
const obj = {name: 'Tom'};
arr.push(obj);
console.log(arr); // 👉️ [{name: 'Tom'}]

Unable to get object instead of array

Hello I am new to the site, and I have a problem with javascript that I do not know how to fix.
I have an array, which I want to turn into an object.
arr = [
{prefer: "sport_swimming", rating: "1"},
{prefer: "sport_running", rating: "5"},
{prefer: "sport_tennis", rating: "2"},
{prefer: "study_archeology", rating: "4"}];
obj = Object.assign({}, arr);
console.log(obj);
I want to get to something like this:
{
"sport": {
"swimming":"1",
"running":"5",
"tennis":"2"
},
"study":
{
"archeology":"4"
}
}
Using reduce you can look over the array and build an object using the keys you split off the property.
const arr = [
{prefer: "sport_swimming", rating: "1"},
{prefer: "sport_running", rating: "5"},
{prefer: "sport_tennis", rating: "2"},
{prefer: "study_archeology", rating: "4"}
];
const out = arr.reduce((acc, data) => {
const parts = data.prefer.split("_");
acc[parts[0]] = acc[parts[0]] || {};
acc[parts[0]][parts[1]] = data.rating;
return acc;
}, {});
console.log(out);
You can use reduce:
const arr = [
{ prefer: "sport_swimming", rating: "1" },
{ prefer: "sport_running", rating: "5" },
{ prefer: "sport_tennis", rating: "2" },
{ prefer: "study_archeology", rating: "4" }];
const result = arr.reduce((a, e) =>
([parent, child] = e.prefer.split('_'),
(a[parent] ??= {})[child] = e.rating,
a), {});
console.log(result);

joining and grouping and counting two javascript objects

I try to get an object like:
var result = [{ "surveyCode":"C", "count": 1}, {"surveyCode":"A", count: 4}]
by joining the two objects on surveyCode and counting the items in object a for each selected surveyCode.
I also can't link a map after merge. Any thoughts?
My attempt is:
var a = [{"id":319268,"surveyCode":"A", "field3": 4},
{"id":319269,"surveyCode":"A", "field3": 4},
{"id":268393,"surveyCode":"A", "field3": 4},
{"id":319266,"surveyCode":"A", "field3": 5},
{"id":319267,"surveyCode":"C", "field3": 4},
{"id":319267,"surveyCode":"B", "field3": 5}];
var b = [{"surveyCode":"C"},{"surveyCode":"A"}]
var merge = function() {
var obj = {},
i = 0,
il = arguments.length,
key;
for (; i < il; i++) {
for (key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
};
function groupBy(data, property) {
return data.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = 0;
}
acc[key]++;
return acc;
}, {});
};
var allGroupedBySurveyCode = groupBy(a, 'surveyCode'); // returns [{ "A": 4}, {"B":1}, {"C": 1}]
var keepOnlyJoinedSurveyCodes = merge(c, allGroupedBySurveyCode); // doesn't work - expects common key e.g. surveyCode, not A.
You could count the occurance of surveyCode and map the count by the grouped array.
var data = [{ id: 319268, surveyCode: "A", field3: 4 }, { id: 319269, surveyCode: "A", field3: 4 }, { id: 268393, surveyCode: "A", field3: 4 }, { id: 319266, surveyCode: "A", field3: 5 }, { id: 319267, surveyCode: "C", field3: 4 }, { id: 319267, surveyCode: "B", field3: 5 }],
groups = [{ surveyCode: "C" }, { surveyCode: "A" }],
counts = data.reduce((r, { surveyCode }) => (r[surveyCode] = (r[surveyCode] || 0) + 1, r), {}),
result = groups.map(({ surveyCode }) => ({ surveyCode, count: counts[surveyCode] }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Array.map and Array.reduce to count the number of data
const a = [{
id: 319268,
surveyCode: 'A',
field3: 4,
},
{
id: 319269,
surveyCode: 'A',
field3: 4,
},
{
id: 268393,
surveyCode: 'A',
field3: 4,
},
{
id: 319266,
surveyCode: 'A',
field3: 5,
},
{
id: 319267,
surveyCode: 'C',
field3: 4,
}
];
const b = [{
surveyCode: 'C',
}, {
surveyCode: 'A',
}];
// We are going to create a new array named "count"
// the array will have the same number of entry as 'b'
// Array.map will loop on every item of the 'b' array and execute a function
// the result of the function for each entry will be the entry of the
// new array
const count = b.map(x => ({
// we copy all the key of the 'b' entry on the new element
...x,
// we are going to count the number of time the surveyCode is
// present on the 'a' array, for this we use of Array.reduce
// Array.reduce will start with a value and loop on every entry of 'a'
// What we do is simple, is the surveyCode the same ?
// > yes? count +1, > no? count +0
count: a.reduce((tmp, {
surveyCode,
}) => (surveyCode === x.surveyCode ? tmp + 1 : tmp), 0),
}));
console.log(count);
Irrelevant :
When you are coding in es6+ try to be consistent. Use of const and let instead of var which is legacy javascript. The use of Array.reduce tells me that you are not coding legacy.
Any issue using lodash?
I'd probably reach straight for:
https://lodash.com/docs/#countBy
You could map over the survey codes and count each entry in a for that particular survey code. Code would look something like this
const a = [
{id: 319268, surveyCode: 'A', field3: 4},
{id: 319269, surveyCode: 'A', field3: 4},
{id: 268393, surveyCode: 'A', field3: 4},
{id: 319266, surveyCode: 'A', field3: 5},
{id: 319267, surveyCode: 'C', field3: 4},
{id: 319267, surveyCode: 'B', field3: 5}
];
const b = [{surveyCode: 'C'}, {surveyCode: 'A'}];
const result = b.map((item) => {
return {...item, count: a.filter(({surveyCode}) => surveyCode === item.surveyCode).length};
});
You can try using reduce.
Loop over data, filter data based on array b and property
Check if passed property from current element is present on op or not, if present increase count by 1 else set it with desired value and then increase count by 1
Take the values
var a = [{"id":319268,"surveyCode":"A", "field3": 4},
{"id":319269,"surveyCode":"A", "field3": 4},
{"id":268393,"surveyCode":"A", "field3": 4},
{"id":319266,"surveyCode":"A", "field3": 5},
{"id":319267,"surveyCode":"C", "field3": 4},
{"id":319267,"surveyCode":"B", "field3": 5}];
function groupBy(data, property) {
var b = [{ "surveyCode": "C" }, { "surveyCode": "A" }].map(v => v[property])
let filteredData = data.filter(v => b.includes(v[property]))
return Object.values(filteredData.reduce((op, inp) => {
op[inp[property]] = op[inp[property]] || {
[property]: inp[property],
count: 0
}
op[inp[property]].count++
return op
}, {}))
}
console.log(groupBy(a, 'surveyCode'))

How to add values to keys inside an object in an array from other array in javascript

I have an array like below
I am trying to add some value by replacing null inside the object inside the array.
The values I wanted to add is from different array "y"
let toBesubmitted = [
{a: null, id: "a"},
{b: null, id: "b"},
{c: null, id: "c"},
{d: null, id: "d"},
{e: null, id: "e"}
]
Another array
let y= ["apple", "ball", "cat", "dog", "elephant"]
How can I achieve this?
You can do that by using a forEach loop on the array and assigning a value to the item[item.id] property at a specific index of the y array:
let toBesubmitted = [
{a: null, id: "a"},
{b: null, id: "b"},
{c: null, id: "c"},
{d: null, id: "d"},
{e: null, id: "e"}
]
let y= ["apple", "ball", "cat", "dog", "elephant"]
toBesubmitted.forEach((item, index) => item[item.id] = y[index]||null);
console.log(toBesubmitted)
A simple loop would do it, if toBeSubmitted[0].a should be y[0] and the id property tells us which property to set:
for (let i = 0; i < toBesubmitted.length; ++i) {
toBesubmitted[i][toBesubmitted[i].id] = y[i];
}
Example:
let toBesubmitted = [
{a: null, id: "a"},
{b: null, id: "b"},
{c: null, id: "c"},
{d: null, id: "d"},
{e: null, id: "e"}
];
let y = ["apple", "ball", "cat", "dog", "elephant"];
for (let i = 0; i < toBesubmitted.length; ++i) {
toBesubmitted[i][toBesubmitted[i].id] = y[i];
}
console.log(toBesubmitted);
This is not the best answer though but try this:
//print object
toBesubmitted.forEach(function(element, key){
for(let e in element){
if(e == Object.keys(element)[0])
element[e] = y[key];
}
});
Console.log(toBesubmitted);
Assuming toBesubmitted[index][key] is y[index][0]
This answer doesn't rely on index being in a particular order.
let toBesubmitted = [
{ a: null, id: "a" },
{ b: null, id: "b" },
{ c: null, id: "c" },
{ d: null, id: "d" },
{ e: null, id: "e" }
];
let y= ["apple", "ball", "cat", "dog", "elephant"];
y.forEach( c => {
const prop = toBesubmitted.find(tbs => tbs.id === c[0]);
if(prop){
prop[c[0]] = c;
}
});
You can also use reduce function like below;
let toBesubmitted = [
{a: null, id: "a"},
{b: null, id: "b"},
{c: null, id: "c"},
{d: null, id: "d"},
{e: null, id: "e"}
];
let y = ["apple", "ball", "cat", "dog", "elephant"];
toBesubmitted.reduce( (acc,curr,idx) => curr[curr.id] = y[idx], {} );
console.log(toBesubmitted);
EDITED
let toBesubmitted = [
{a: null, id: "a"},
{b: null, id: "b"},
{c: null, id: "c"},
{d: null, id: "d"},
{e: null, id: "e"}
]
let y= ["apple", "ball", "cat", "dog", "elephant"]
toBesubmitted.forEach((item, index) => {
Object.keys(item).forEach(key => {
if (item[key] === null) {
item[key] = y[index];
}
})
})
console.log(toBesubmitted);

Grouping elements in javascript

I've created this list by grouping elements from another list (with d3.nest)
array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3},
{Id: "1234b", ECTS: 3}]},
{key: "7S", values: [{Id: "1534a", ECTS: 5},
{Id: "154b", ECTS: 4},]} ]
From this list I want to create something like this:
array = [{key: "6S", values: { 3: [{Id: "1234a"}, {Id: "1234b"}]}},
{key: "7S", values: { 5: [{Id: "1534a"}], 4: [{Id:"1534a"}]}}]
Actually I want to group the data for each key (6S, 7S) by ECTS.
I've tried with _.groupBy.... but is not working. The problem is that the elements that I want to group are objects, already grouped once.
Any idea about how I could group the items?
You can try following
var array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", ECTS: 5}, {Id: "154b", ECTS: 4},]} ];
array.forEach((obj) => {
var values = {};
// Iterate over array and create the updated value
obj.values.forEach((item) => {
values[item.ECTS] = values[item.ECTS] || [];
values[item.ECTS].push({"Id" : item.Id});
});
// Set the updated value in object
obj.values = values;
});
console.log(array);
var array = [{
key: "6S",
values: [{
Id: "1234a",
ECTS: 3
},
{
Id: "1234b",
ECTS: 3
}
]
},
{
key: "7S",
values: [{
Id: "1534a",
ECTS: 5
},
{
Id: "154b",
ECTS: 4
},
]
}
]
array = array.map(function(v1) {
var updatedVal = v1.values.reduce(function(obj, v2) {
obj[v2.ECTS] = obj[v2.ECTS] || [];
obj[v2.ECTS].push({
Id: v2.Id
});
return obj;
}, {});
v1.values = updatedVal;
return v1;
});
console.log(array);

Categories