Getting values from array of objects - javascript

I've got an array of objects
var arr1 = [{
"amount": 700,
"hits": 4,
"day": 1
},
{
"amount": 100,
"hits": 7,
"day": 4
},
{
"amount": 500,
"hits": 3,
"day": 8
}
];
What I need is to create a new array of objects, with key "param" in each object, and the value of "param" should be equals to "amount" field in arr1 objects.
Expected output:
var newArr = [{
"param": 700
},
{
"param": 100
},
{
"param": 500
}
];

You can user Array.prototype.map():
var arr1 = [{"amaunt": 700,"hits": 4,"day": 1}, {"amaunt": 100,"hits": 7,"day": 4}, {"amaunt": 500,"hits": 3,"day": 8}],
newArr = arr1.map(function(elem) {
return {param: elem.amaunt};
});
console.log(newArr);

Try using map:
var arr1 = [
{
"amaunt": 700,
"hits":4,
"day":1
},
{
"amaunt": 100,
"hits":7,
"day":4
},
{
"amaunt": 500,
"hits":3,
"day":8
}
];
var arr2 = arr1.map(function(obj) {
return {param: obj.amaunt};
});
console.log(arr2);

var newArr = []
arr1.forEach(obj => {
newArr.push({param: obj.amount});
});

You can try this
var arr1 = [
{
"amaunt": 700,
"hits":4,
"day":1
},
{
"amaunt": 100,
"hits":7,
"day":4
},
{
"amaunt": 500,
"hits":3,
"day":8
}
];
var newArr=[];
arr1.forEach(function(item){
newArr.push({"param":item.amaunt});
});
console.log(newArr);

Try this
arr1.forEach(function(data){
var obj = {"param": data.amount};
newArr.push(obj);
})
Fiddle here

Another way you can do this
var newArr=[];
arr1.map(function(obj) {
newArr.push("param:"+obj.amaunt);
});

Related

iterate an array of object and separe comparing dates in es6

I need to make a function to iterate an array of x objects then compare the date inside the objects and separate in different arrays so I can show separately in the HTML, this is my object:
[{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]
I want something like this:
obj1 = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141}]
obj2 = [{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}]
my code:
// global variables
json = [{
"id": 1,
"date": "2020-02-06",
"value": 131
}, {
"id": 2,
"date": "2020-02-06",
"value": 135
}, {
"id": 3,
"date": "2020-02-06",
"value": 141
}, {
"id": 4,
"date": "2020-02-05",
"value": 151
}, {
"id": 6,
"date": "2020-02-05",
"value": 155
}];
obj1 = [];
obj2 = [];
for (const x of json) {
if (x.date != x.date) {
obj1.push(x)
} else {
obj2.push(x)
}
}
console.log(obj1);
console.log(obj2);
in result always the items push into the obj1..
any help is welcome.
The typical solution for this is to group them by the key and push them to an array. Below is an example using Array reduce and Object.values to get it down to the two arrays.
var items = [
{"id":1,"date":"2020-02-06","value":131},
{"id":2,"date":"2020-02-06","value":135},
{"id":3,"date":"2020-02-06","value":141},
{"id":4,"date":"2020-02-05","value":151},
{"id":6,"date":"2020-02-05","value":155}
]
var dateGroups = items.reduce( function (dates, item) {
dates[item.date] = dates[item.date] || []
dates[item.date].push(item)
return dates
}, {})
var results = Object.values(dateGroups)
console.log(results)
You could goup by date and get an array of arrays.
var data = [{ id: 1, date: "2020-02-06", value: 131 }, { id: 2, date: "2020-02-06", value: 135 }, { id: 3, date: "2020-02-06", value: 141 }, { id: 4, date: "2020-02-05", value: 151 }, { id: 6, date: "2020-02-05", value: 155 }],
grouped = data.reduce((r, o) => {
var group = r.find(([{ date }]) => date === o.date);
if (!group) r.push(group = []);
group.push(o);
return r;
}, []);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use reduce to build an object that maps each unique date to its respective data items, having, basically, a group by date:
const data = [{"id":1,"date":"2020-02-06","value":131},{"id":2,"date":"2020-02-06","value":135},{"id":3,"date":"2020-02-06","value":141},{"id":4,"date":"2020-02-05","value":151},{"id":6,"date":"2020-02-05","value":155}];
const groupedData = data.reduce((acc, curr) => ({
...acc,
[curr.date]: [...(acc[curr.date] || []), curr]
}), {});
console.log(groupedData);
We also use above the spread syntax and computed property names to make the code shorter.

Push same multiple objects into multiple arrays based on another value from object

This is a follow up to again Push same multiple objects into multiple arrays.
AFter I create my objects:
let objName = ["object1", "object2", "object3"];
let xyzArr = ["xyz1", "xyz2", "xyz3"];
let theArr = [[], [], []];
let objects = [];
objName.forEach((name, index) => {
objects.push({
xyz: xyzArr[index],
arr: theArr[index]
});
});
And push values using #NickParsons solution:
$.getJSON(json, result => {
result.forEach(elem => {
objects.forEach(obj => {
obj.arr.push({
x: elem.date,
y: elem.val2
});
});
});
});
Here I am adding my objects, i.e. x and y based on no condition. But I want to add it based on if indexOf(obj.xyz) = elem.val1.
THis is my JSON:
[
{
"date": "2019-07-21",
"val1": "xyz1_hello",
"val2": 803310
},
{
"date": "2019-07-22",
"val1": "xyz2_yellow",
"val2": 23418
},
{
"date": "2019-07-22",
"val1": "xyz1_hello",
"val2": 6630
},
{
"date": "2019-07-24",
"val1": "xyz2_yellow",
"val2": 4
},
{
"date": "2019-07-21",
"val1": "xyz3_yo",
"val2": 60984
}
]
Is there a way for me to push values to x and y if obj.xyz is LIKE (indexOF) elem.val1 For example, if indexOf(obj.xyz) = elem.val1, then push their corresponding elem.date and elem.val2 data to obj.arr.
Assuming you have some boolean like(a,b) function that decides if two values are similar or not, and your elements are in elems:
objects.forEach(o =>
elems.forEach(e => {
if(like(o.xyz, e.val1)){
o.arr.push({
x: e.date,
y: e.val2
});
}
}));

Returning mutated object with some key modified using spread operator

In the below object, I want to increment the value of data[1]'s val by 1, and leave everything unchanged, how can I achieve it?
const state =
{
"data": [{
"val": 1,
"other": 10
},
{
"val": 11,
"other": 100
},
{
"val": 100,
"other": 1000
}
]
}
I want the mutated object to be like this-
{
"data": [{
"val": 1,
"other": 10
},
{
"val": 10,
"other": 100
},
{
"val": 100,
"other": 1000
}
]
}
I know that I can change the value directly like this- state.data[1].val = state.data[1].val+1, but I want to achieve the same using spread operator, is it possible to achieve it using spread operator?
Somthing like this-
const mutatedState = {
...state,
data: [...state.data]
}
Get the data out of the object. And use like this
const state = { "data": [{ "val": 1, "other": 10 }, { "val": 11, "other": 100 }, { "val": 100, "other": 1000 } ] }
const {data} = state;
let res = {
...state,
data:[
data[0],
{...data[1],val:data[1].val+ 1},
...data.slice(2)
]
}
console.log(result)
You could assign parts of the array/objects.
var object = { data: [{ val: 1, other: 10 }, { val: 10, other: 100 }, { val: 100, other: 1000 }] },
result = {
...object,
data: Object.assign(
[...object.data],
{
1: Object.assign(
{},
object.data[1],
{ val: object.data[1].val + 1 }
)
}
)
};
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With a bit help of some functional helpers that is actually quite elegant:
const mapOne = (index, mapper) => array => array.map((it, i) => i === index ? mapper(it) : it);
const lens = (key, mapper) => obj => ({ ...obj, [key]: mapper(obj[key]) });
// somewhere
this.setState(mapOne(1, lens("val", it => it + 1)));

How to get one json object format from another JSON format

Maybe this question has already been asked and answered somewhere but after searching for more than 3 hrs I'm asking this question.
Below is my JSON data
var my_data = [
{
"TempRture_qc": 4,
"VoltAGE": 44.09722,
"TempRture": 22.32,
"VoltAGE_qc": 55,
"_time": "2018-08-07T03:39:29.001Z"
},
{
"TempRture_qc": 2,
"VoltAGE": 42.09722,
"TempRture": 22.12,
"VoltAGE_qc": 0,
"_time": "2018-08-07T03:39:30.006Z"
},
{
"TempRture_qc": 1,
"VoltAGE": 43.09722,
"TempRture": 22.82,
"VoltAGE_qc": 0,
"_time": "2018-08-07T03:39:31.009Z"
}
];
desired output i need
[
{
"name": "TempRture_qc",
"data": [
{"name":"2018-08-07T03:39:29.001Z","y":4},
{"name":"2018-08-07T03:39:30.006Z","y":2},
{"name":"2018-08-07T03:39:33.017Z","y":1}
]
},
{
"name": "VoltAGE",
"data": [
{"name":"2018-08-07T03:39:29.001Z","y":44.09722},
{"name":"2018-08-07T03:39:30.006Z","y":42.09722},
{"name":"2018-08-07T03:39:33.017Z","y":43.09722}
]
},
{
"name": "TempRture",
"data": [
{"name":"2018-08-07T03:39:29.001Z","y":22.32},
{"name":"2018-08-07T03:39:30.006Z","y":22.12},
{"name":"2018-08-07T03:39:33.017Z","y":22.82}
]
},
{
"name": "VoltAGE_qc",
"data": [
{"name":"2018-08-07T03:39:29.001Z","y":55},
{"name":"2018-08-07T03:39:30.006Z","y":0},
{"name":"2018-08-07T03:39:33.017Z","y":0}
]
}
]
for getting this above output i have tried below code.
var accounting = [];
var fieldName = {};
for (var x in obj){
var mykey = Object.keys(obj[x]);
for (var mk in mykey){
if(mykey[mk]=='VoltAGE'){
fieldName.name = mykey[mk];
// accounting.push({
// "name":mykey[mk]
// })
}
if(mykey[mk]=='TempRture'){
fieldName.name = mykey[mk];
}
// console.log(mykey[mk]); //to get the key name
}
accounting.push({
"name" : obj[x]._time,
"y" : obj[x][employees.name],
})
fieldName.data = accounting;
}
console.log(fieldName );
by doing this what I'm getting is below JSON
{ name: 'TempRture',
data:
[ { name: '2018-08-07T03:39:29.001Z', y: 22.32 },
{ name: '2018-08-07T03:39:32.014Z', y: 22.12 },
{ name: '2018-08-07T03:39:33.017Z', y: 22.82 } ] }
I'm not able to understand how I will get the data in one JSON object.
For a solution with low time complexity, try .reduceing into an object indexed by keys of the inner object, creating a { name, data: [] } at that key in the accumulator if it doesn't exist there yet. Then, push to the data array, and get the values of the whole object:
var my_data=[{"TempRture_qc":4,"VoltAGE":44.09722,"TempRture":22.32,"VoltAGE_qc":55,"_time":"2018-08-07T03:39:29.001Z"},{"TempRture_qc":2,"VoltAGE":42.09722,"TempRture":22.12,"VoltAGE_qc":0,"_time":"2018-08-07T03:39:30.006Z"},{"TempRture_qc":1,"VoltAGE":43.09722,"TempRture":22.82,"VoltAGE_qc":0,"_time":"2018-08-07T03:39:31.009Z"}]
console.log(Object.values(
my_data.reduce((a, { _time, ...obj }) => {
Object.entries(obj).forEach(([name, val]) => {
if (!a[name]) a[name] = { name, data: [] };
a[name].data.push({ name: _time, y: val });
});
return a;
}, {})
));
var my_data=[{"TempRture_qc":4,"VoltAGE":44.09722,"TempRture":22.32,"VoltAGE_qc":55,"_time":"2018-08-07T03:39:29.001Z"},{"TempRture_qc":2,"VoltAGE":42.09722,"TempRture":22.12,"VoltAGE_qc":0,"_time":"2018-08-07T03:39:30.006Z"},{"TempRture_qc":1,"VoltAGE":43.09722,"TempRture":22.82,"VoltAGE_qc":0,"_time":"2018-08-07T03:39:31.009Z"}]
var keys = Object.keys(my_data[0])
var result= [];
for(i = 0; i<keys.length-1; i++) {
var obj = {name: keys[i],data: []}
obj.data = my_data.map(val=>({name: val["_time"], y: val[keys[i]]}));
result.push(obj);
}
console.log(result)
An understandable answer with map, findIndex and forEach functions will be
var my_data = [{ "TempRture_qc": 4, "VoltAGE": 44.09722, "TempRture": 22.32, "VoltAGE_qc": 55, "_time": "2018-08-07T03:39:29.001Z" }, { "TempRture_qc": 2, "VoltAGE": 42.09722, "TempRture": 22.12, "VoltAGE_qc": 0, "_time": "2018-08-07T03:39:30.006Z" }, { "TempRture_qc": 1, "VoltAGE": 43.09722, "TempRture": 22.82, "VoltAGE_qc": 0, "_time": "2018-08-07T03:39:31.009Z" } ],
result = [];
my_data.map(itm => {
let keys = Object.keys(itm);
keys.forEach(iitt => {
if (iitt != '_time') {
let index = result.findIndex(ii => {
return ii.name == iitt;
})
if (index == -1) {
result.push({
name: iitt,
data: []
});
result[result.length - 1].data.push({
name: itm["_time"],
y: itm[iitt]
})
} else {
result[index].data.push({
name: itm["_time"],
y: itm[iitt]
});
}
}
})
})
console.log(result)

Find duplicated element in array of objects

I have few arrays of JSON objects.I need to iterate over the arrays and return true if there are two or more elements with the same userId value.
[{
"name":"John",
"age":30,
"userId": 5,
}],
[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],
[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]
Here is my method so far, I'm iterating over the array and checking is there a user with 506 userId presence.
isPostedMultiple = (data) => {
for (let j = 0; j < data.length; j++) {
if (data[j].UserId == '506') {
console.log('506 data :', data[j]);
} else {
console.log('not 506 data');
}
}
}
First of all the Object you have given is erroneous. Make it correct. Coming to the problem,
You can use a combination of Array.prototype.some and Array.prototype.filter.
data.some(
(el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);
To check if there exists more than one element matching certain condition.
var data = [{
"name": "John",
"age": 30,
"userId": 5,
},
{
"name": "Benjamin",
"age": 17,
"userId": 5,
},
{
"name": "Johnatan",
"age": 35,
"userId": 10,
}
];
var result = data.some(
(el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);
console.log(result)
You can merge arrays using array spread syntax and than use the reduce with the filter method
const mergedArrays = [...arr1, ...arr2, ...arr3];
const isDublicated = mergedArrays.reduce(
(acc, item) => acc || mergedArrays.filter(user => user.userId === item.userId) > 1,
false
);
To achieve expected result, use below option of using filter and findIndex to iterate over every array and compare userId
var x = [[{
"name":"John",
"age":30,
"userId": 5,
}],
[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],
[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]]
x = x.filter((v, i, self) =>
i === self.findIndex((y) => (
y[0].userId === v[0].userId
))
)
console.log(x);
code sample - https://codepen.io/nagasai/pen/wmWqdY?editors=1011
var jsonObj1 = [{
"name":"John",
"age":30,
"userId": 5
},
{
"name":"Benjamin",
"age":17,
"userId": 5
},
{
"name":"Johnatan",
"age":35,
"userId": 10
}];
var jsonObj2 = [{
"name":"John",
"age":30,
"userId": 5
},
{
"name":"Benjamin",
"age":17,
"userId": 15
},
{
"name":"Johnatan",
"age":35,
"userId": 10
}];
var logger = document.getElementById('logger');
logger.innerHTML = "";
function checkForDupIds(jsonObj, headerStr) {
var logger = document.getElementById('logger');
var hasDups = [];
var items = [];
for(var a=0;a<jsonObj.length;a++) {
if (items.includes(jsonObj[a].userId)) {
hasDups.push(jsonObj[a].userId);
} else {
items.push(jsonObj[a].userId);
}
}
logger.innerHTML += "<h1>" + headerStr + "</h1>";
for(var b=0;b<hasDups.length;b++) {
logger.innerHTML += "<div>" + hasDups[b] + "</div>\n";
console.log(hasDups[b]);
}
if (hasDups.length === 0) {
logger.innerHTML += "<div>No Duplicates Found</div>\n";
}
}
checkForDupIds(jsonObj1, "jsonObj1");
checkForDupIds(jsonObj2, "jsonObj2");
<html>
<body>
<div id='logger'></div>
</body>
</html>
You can loop over the array and keep a count of how many times each userId value appears. If you get to 2 for any value, stop and return false (or some other suitable value).
Array.prototype.some allows looping over the array until the condition is true, so it only loops over the source once. The data in the OP was invalid, I've modified it to be an array of objects.
var data = [{
"name":"John",
"age":30,
"userId": 5
},
{
"name":"Benjamin",
"age":17,
"userId": 5
},
{
"name":"Johnatan",
"age":35,
"userId": 10
}]
function hasDupIDs(data) {
// Store for userId values
var ids = {};
// Loop over values until condition returns true
return data.some(function(x) {
// If haven't seen this id before, add to ids
if (!ids.hasOwnProperty(x.userId)) ids[x.userId] = 0;
// Increment count
ids[x.userId]++;
// Return true if second instance
return ids[x.userId] > 1;
});
}
console.log(hasDupIDs(data));
If you want more concise code, you can use:
var data = [
{"name":"John","age":30,"userId": 5},
{"name":"Benjamin","age":17,"userId": 5},
{"name":"Johnatan","age":35,"userId": 10}];
function hasDupIDs(data) {
var ids = {};
return data.some(x => {
ids[x.userId] || (ids[x.userId] = 0);
return ++ids[x.userId] > 1;
});
}
console.log(hasDupIDs(data));

Categories

Resources