JavaScript: take properties from multiple objects and assign to one - javascript

So im working with an array of objects that requires data from multiple objects to be put into one dependant on the date within those objects.
The starting object looks like this:
[
{
"LOCATION":17,
"Stock_In_Area":39.0709838867,
"DATE_DT":"2021-03-07",
},
{
"LOCATION":17,
"Stock_In_Area":41.8843955994,
"DATE_DT":"2021-03-14",
},
{
"LOCATION":612,
"Stock_In_Area":8.4867076874,
"DATE_DT":"2021-03-07",
},
{
"LOCATION":612,
"Stock_In_Area":9.2035646439,
"DATE_DT":"2021-03-14",
},
];
and im trying to get something like this:
{
"17":39.0709838867,
"612":8.4867076874,
"date":"2021-03-07",
},
{
"17":41.8843955994,
"612":9.2035646439,
"date":2021-03-14
},
So the object would be
{
[location]: stock_in_area
date: DATE_DT
}
where the two locations have the same date value

I would have maintained a hash kind of variable in memory and compared each item from array wrt to the value present in the hash.
let ip = [{
"LOCATION": 17,
"Stock_In_Area": 39.0709838867,
"DATE_DT": "2021-03-07",
},
{
"LOCATION": 17,
"Stock_In_Area": 41.8843955994,
"DATE_DT": "2021-03-14",
},
{
"LOCATION": 612,
"Stock_In_Area": 8.4867076874,
"DATE_DT": "2021-03-07",
},
{
"LOCATION": 612,
"Stock_In_Area": 9.2035646439,
"DATE_DT": "2021-03-14",
},
];
const _enum = {};
const op = [];
for (let i = 0; i < ip.length; i++) {
let _k = ip[i].DATE_DT;
if (!_enum[_k]) {
_enum[_k] = _k;
op.push({
date: _k,
[ip[i].LOCATION]: ip[i].Stock_In_Area
});
} else {
const found = op.find(el => el.date === _k);
found[ip[i].LOCATION] = ip[i].Stock_In_Area;
}
}
console.log(op);

Related

Loop through nested array to return values of object

I have a nested array and what I was trying to do was get all the values of the object embedded inside the array. I am currently getting each embedded object and calling Object.values to get the values but this method isn't efficient when the array size is big. Is there a way to loop through the array and return the values of each object? Any help is appreciated. Thanks in advance.
const data = [{"path":"uploads\\20211115000755-package.json"},{"path":"uploads\\20211115012255-index.html"},{"path":"uploads\\20211115014342-dataServerMid.js"},{"path":"uploads\\20211115031212-index.js"},{"path":"uploads\\20211115031218-uploadDataServer.js"},{"path":"uploads\\20211115031232-index.js"},{"path":"uploads\\20211115031244-dataServerMid.js"},{"path":"uploads\\20211115031250-uploadData.css"},{"path":"uploads\\20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115031318-20211115031303-20211115012255-index.html"},{"path":"uploads\\20211115050204-exportsCapture.JPG"},{"path":"uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"},{"path":"uploads\\20211115200304-Readme.docx"},{"path":"uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"},{"path":"uploads\\20211115203354-ln command examples.docx"},{"path":"uploads\\20211115210027-Q2.docx"},{"path":"uploads\\20211116011817-Fall 2019 ABCD Plattsburgh Syllabi Course Description.docx"}]
//change this to loop and return all the values instead of having to call by index
const dataValues = [Object.values(data[0]).toString(), Object.values(data[1]).toString(), Object.values(data[2]).toString()]
console.log(dataValues)
UPDATE: I tried #yousaf's method. It worked for my 3 item array but not for this:
const data = [{
"path": "uploads\\20211115000755-package.json"
}, {
"path": "uploads\\20211115012255-index.html"
}, {
"path": "uploads\\20211115014342-dataServerMid.js"
}, {
"path": "uploads\\20211115031212-index.js"
}, {
"path": "uploads\\20211115031218-uploadDataServer.js"
}, {
"path": "uploads\\20211115031232-index.js"
}, {
"path": "uploads\\20211115031244-dataServerMid.js"
}, {
"path": "uploads\\20211115031250-uploadData.css"
}, {
"path": "uploads\\20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115031318-20211115031303-20211115012255-index.html"
}, {
"path": "uploads\\20211115050204-exportsCapture.JPG"
}, {
"path": "uploads\\20211115052347-[FREE] Stunna 4 Vegas x DaBaby x NLE Choppa Type Beat Call of Duty (320 kbps).mp3"
}, {
"path": "uploads\\20211115200304-Readme.docx"
}, {
"path": "uploads\\20211115202751-Visual Artist Series Fall 2019Corrected.docx"
}, {
"path": "uploads\\20211115203354-ln command examples.docx"
}, {
"path": "uploads\\20211115210027-Q2.docx"
}, {
"path": "uploads\\20211116011817-Fall 2019.docx"
}]
//change this to loop and return all the values instead of having to call by index
const dataValues = data.map((obj, idx) => obj["path" + (idx + 1)])
console.log(dataValues)
Use a for...of to iterate over the array, and then push the value to a new array.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = [];
for (const obj of data) {
const [value] = Object.values(obj);
arr.push(value);
}
console.log(arr);
Or you can use map.
const data=[{path1:"uploads\\20211115000755-package.json"},{path2:"uploads\\20211115012255-index.html"},{path3:"uploads\\20211115014342-dataServerMid.js"}];
const arr = data.map(obj => {
const [value] = Object.values(obj);
return value;
});
console.log(arr);
Use for loop for iterate data
const data = [{
"path1": "uploads\\20211115000755-package.json"
}, {
"path2": "uploads\\20211115012255-index.html"
}, {
"path3": "uploads\\20211115014342-dataServerMid.js"
}]
const dataValues = [];
for(var i = 0; i < data.length; i++)
{
dataValues.push(Object.values(data[i]).toString())
}
console.log(dataValues)
This may help You. Try it out..
function nestedLoop(obj) {
const res = {};
function recurse(obj, current) {
for (const key in obj) {
let value = obj[key];
if(value != undefined) {
if (value && typeof value === 'object') {
recurse(value, key);
} else {
// Do your stuff here to var value
res[key] = value;
}
}
}
}
recurse(obj);
return res;
}

Push items in an array in Javascript?

I'm working on school-app. person enter students marks from frontend and I've to store it in my backend. I know my data-structure is quite bad. but this is only way I can comfortly use and fit it in my front end application/website.
codeSandbox link
Full Code:
//This data is already set need to push information in this array.
let student = [{
"detail": {
"name": "Mark",
"surname":"widen"
},
}];
//formatting the query in json.
const keys = Object.keys(query)[0].split(",")
const values = Object.values(query)[0].split(",")
const newObj = {}
for (let i = 0; i < keys.length; i++) {
newObj[keys[i]] = values[i]
}
// I've to push it along with "academic-year". so,
for (let a = 0; a < newObj.length; a++) {
const year = a + "st-Year"
console.log(year) // Expected Output: 1st-Year and 2nd-Year
}
// How to run this both for-loop synchronously way ?? AND
//pushing with "ObtainedMarks" and "year" (Error over here)
student.push({
ObtainedMarks: {
year : [
{ physics: newObj }
],
year : [
{ physics: newObj }
]
}
})
console.log(student) //Here's I want expected Output
Expected Output:
let student = [{
"detail": {
"name": "Mark",
"surname":"widen"
},
ObtainedMarks: {
"1st-Year": [
{ physics: { "marks": "500" } } //Physics subject is default.
],
"2nd-Year": [
{ physics: { "mark": "200" } } //Physics subject is default.
]
}
}];
I want to push returned data in student array. with 1st-Year
and 2nd-Year's for-loop.
You can do the conversion in your for-loop
let student = [{
"detail": {
"name": "Mark",
"surname": "widen"
},
}];
let query = {
"marks,mark": "500,200"
}
const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");
const marks = {}
for (let i = 0; i < keys.length; i++) {
marks[i === 0 ? `${i+1}st-year` : `${i+1}nd-year`] = [{
physics: {
[keys[i]]: values[i]
}
}];
}
student.push({
obtainedMarks: marks
});
console.log(student);
Alternative way: map through the keys and create an object from entries after manipulating the data.
let student = [{
"detail": {
"name": "Mark",
"surname": "widen"
},
}];
let query = {
"marks,mark": "500,200"
}
const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");
const marks = Object.fromEntries(keys.map((k, i) => {
return [
i === 0 ? `${i+1}st-year`: `${i+1}nd-year`,
[{ physics: { [k]: values[i] }}]
];
}));
student.push({
obtainedMarks: marks
});
console.log(student);

Seperate values based on property value and show with javascript

I have an array that looks like this:
var array = [[
{ "loc": {} },
{ "distance": 6.4 },
{ "zip1": "06120" },
{ "zip2": "06095" },
{ "group": 1 },
{ "weight": 1119 }
], [
{ "loc": {} },
{ "distance": 6.41 },
{ "zip1": "06095" },
{ "zip2": "06120" },
{ "group": 2 },
{ "weight": 41976 }
], [
{ "loc": {} },
{ "distance": 6.41 },
{ "zip1": "06095" },
{ "zip2": "06120" },
{ "group": 1 },
{ "weight": 41976 }
]];
Now I want to take the array values based on the property values for show in HTML.
Expected output is split into array with "group" property. I also need to store in HTML with based on group, as shown in the example below:
group 1:
all zip1's under group 1
group 2:
all zip1's under group 2
I tried using a loop but I didn't manage to get the right answer:
for (var k = 0; k < array.length; k++) {
var array1 = array[k];
if (flag[array1[2]["zip1"]]) continue;
flag[array1[2]["zip1"]] = true;
output2.push(array1);
}
So help me to find split the array show in HTML with group wise
Using reduce, you can create an object with each group value as key and an array of zip1 as values like this:
Then loop through the Object.entries, to create the HTML:
const array = [[{"loc":{}},{"distance":6.4},{"zip1":"06120"},{"zip2":"06095"},{"group":1},{"weight":1119}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":2},{"weight":41976}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":1},{"weight":41976}]];
const merged = array.reduce((r, a) =>{
const { group } = a.find(n => n.group)
const { zip1 } = a.find(n => n.zip1)
r[group] = r[group] || []
r[group].push(zip1)
return r;
},{})
const output = document.getElementById('output');
Object.entries(merged).forEach(([group, zips]) => {
const h1 = document.createElement('h1');
h1.innerHTML = "group " + group
const span = document.createElement('span');
span.innerHTML = `Zip1 - ${zips} (in group - ${group})`;
output.appendChild(h1)
output.appendChild(span)
})
<div id="output"></div>

Javascript - Create and populate associative array containing sub arrays

I'm trying to collate some data. I would like to populate an array containing sub arrays, for example, I have some json data that I am iterating over:
{
"name": "name1",
"prices": "209.67"
},
{
"name": "name1",
"prices": "350"
},
{
"name": "name2",
"price": "195.97"
},
I would like to create an array that ends up looking something like the following:
myArray['name1']prices[0] = 209.67,
prices[1] = 350,
['name2']prices[0] = 195.97
I thought that the code below would achieve what I wanted but it doesn't work. It throws an exception. It doesn't seem to recognise the fact that the prices are an array for a given index into the main array. Instead the prices appear at the same level as the names. I want the main array for a given name to contain an inner array of prices.. Does anybody have any idea how I could modify to make this work?
function doStuff() {
var cryptoData = getData();
var datasetValues = {};
datasetValues.names = [];
datasetValues.names.prices = [];
for (var result = 0; result < cryptoData.length; result++) {
var data = cryptoData[result];
if (datasetValues.names.indexOf(data.cryptoname) === -1)
{
datasetValues.names.push(data.cryptoname);
}
// This works
//datasetValues.names.prices.push(data.prices);
// This doesn't!
datasetValues.cryptoNames[data.cryptoname].prices.push(data.prices);
}
}
You could reduce the array by using an object and take a default object if the property is not set. Then push the price.
var data = [{ name: "name1", price: "209.67" }, { name: "name1", price: "350" }, { name: "name2", price: "195.97" }],
result = data.reduce((r, { name, price }) => {
r[name] = r[name] || { name, prices: [] };
r[name].prices.push(+price);
return r;
}, Object.create(null));
console.log(result);
Try this
function parseData(input){
return input.reduce(function(o,i){
o[i.name] = {};
if(!o[i.name]['prices']){
o[i.name]['prices'] = [];
}
o[i.name]['prices'].push(i.prices);
return o;
},{});
}

Create object array by pushing variables?

I am trying to create something like
var[1] = {object1, object2};
var[2] = {object1, object3);
Or something like that so that I can loop over each result and get all the objects associated with that key. The problem is I am either really tried or something because I can't seem to figure out how to do that.
In PHP I would do something like
$var[$object['id']][] = object1;
$var[$object['id']][] = object2;
How can I do something like that in Javascript?
I have a list of object elements, that have a key value called id and I want to organize them all by ID. Basically...
[0] = { id: 2 },
[1] = { id: 3 },
[2] = { id: 2 },
[3] = { id: 3 }
And I want to have them organized so it is like
[0] = { { id: 2 }, { id: 2 } }
[1] = { { id: 3 }, { id: 3} }
var indexedArray = [];
for(var key in myObjects) {
var myObject = myObjects[key];
if(typeof(indexedArray[myObject.id]) === 'undefined') {
indexedArray[myObject.id] = [myObject];
}
else {
indexedArray[myObject.id].push(myObject);
}
}
console.log(indexedArray);
http://jsfiddle.net/2fr4k/
Array is defined by square brackets:
var myArray = [{ "id": 2 }, { "id": 3 }];
What you had is not a valid syntax.
Using ECMA5 methods, you could do something like this.
Javascript
var d1 = [{
id: 2
}, {
id: 3
}, {
id: 2
}, {
id: 3
}],
d2;
d2 = d1.reduce(function (acc, ele) {
var id = ele.id;
if (!acc[id]) {
acc[id] = [];
}
acc[id].push(ele);
return acc;
}, {});
d2 = Object.keys(d2).map(function (key) {
return this[key];
}, d2);
console.log(JSON.stringify(d2));
Output
[[{"id":2},{"id":2}],[{"id":3},{"id":3}]]
On jsFiddle

Categories

Resources