I have the following js code https://repl.it/N0xy/0
I am trying to push some objects into an existing one using some functions:
mylist.push(createMyObject(item.name, item.school, item.teacher))
the result contains :
{ result: true, count: 1, items: [ [ [Object], [Object] ] ] }
instead of :
{ result: true, count: 1, items: [ { name: 'Jacky', school: 'high', teacher: 'good' },
{ name: 'Tom', school: 'college', teacher: 'bad' } ] }
how can i fix this?
thanks
You forgot to do JSON.stringify(obj) in the last statement. Everything else seems fine.
You might want to change the second last line to:
obj.items = create(); as well.
or maybe obj.items = obj.items.concat(create());
You pushed an array to obj.items in stead of the separate items. create() returns an array.
Try this:
create().forEach(function(item) {
obj.items.push(item);
});
OR
let createdItems = create();
for(item of createdItems) {
obj.items.push(item);
}
In your console.log at the end, wrap the obj in a call to JSON.stringify like this:
console.log("print my obj: ",obj);
Related
I have read several solutions to this problem here. When I try it, I continue to receive an error for the pop() method.
I have what is essentially a multidimensional array in javascript.
I am tasked with returning the array with the sensitive info removed (e.g. remove the SSN, in this example)
I thought I could use a foreach loop, and the pop() function to remove the last element of the child arrays, the SSN.
testing it using node on the commandline, the stdout is telling me that element.pop() is not a function. i've tried it with pop(), slice(), filter(), all with no success.
when running $> node filename.js
H:\Apache2\htdocs\test\filename.js:50
noppi[i] = element.pop();
^
TypeError: element.pop is not a function
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: 'john#example.com',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: 'sally#example.com',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: 'angie#example.com',
SSN: '789'
}
];
let i = 0;
let noppi = [];
recs.forEach(element => {
noppi[i] = element.pop();
i++;
});
console.log(noppi);
At the risk of sounding redundant, I'll briefly reiterate what the earlier answers have already stated.
The input data structure isn't a multi-dimensional array [ [ ... ], [ ... ] ] , it's an array of objects [ {...}, {...} ]. So you can't use Array methods like .pop() on the objects {...}.
Here's a simple one-liner that uses .forEach() and delete.
recs.forEach(obj => delete obj.SSN)
delete is an operator with one purpose: to remove an object's property like for example SSN: '123-45-6789'. Simple and perfect.
Note, .forEach() mutates the array, meaning that it's the original data being changed (see Minja's comment).
let recs = [
{
ID: 1,
NAME: 'John',
EMAIL: 'john#example.com',
SSN: '123'
}, {
ID: 2,
NAME: 'Sally',
EMAIL: 'sally#example.com',
SSN: '456'
}, {
ID: 3,
NAME: 'Angie',
EMAIL: 'angie#example.com',
SSN: '789'
}
];
recs.forEach(obj => delete obj.SSN);
console.log(recs)
Try this:
recs.forEach(element => {
noppi.push = element;
});
You are trying to use pop() on an object not an array
As per your need you need to remove SSN from your object, try below code it should work for you.
recs.forEach(element => {
const { SSN, ...rest } = element;
noppi.push(rest);
});
Here we are removing SSN from object and rest will push in noppi.
I'm using the following Lodash chained utilities to map/flat and array and produce a new one while excluding the undefined valued.
const array = _(resp.data)
.omit(_.isUndefined)
.flatMap('building')
.value()
console.log(array)
And this is the result:
As you can see the undefined values are still being included. Why is this?
EDIT:
resp.data looks like this
[
{ username: '', building: [ name: '' ] }
{ username: '', building: [ name: '' ] }
// etc...
]
EDIT2:
Those undefined values are probably the empty building that come objects have.
The extra undefined value should belong to a user in the resp.data where no building exist. All you have to do is to _.filter() all values that are undefined through _.identity() after the _.flatMap().
Note: Using _.omit should only be used against objects, using this in the context of an array (e.g. _.flatMap() which results in an array) would yield a result of an object wherein the index of each item is it's index in the array. You should use _.filter() instead.
var data = [
{ username: 'user1', building: [ { name: 'building1' } ] },
{ username: 'user2', building: [ { name: 'building2' } ] },
{ username: 'user3' }
];
var result = _(data)
.flatMap('building')
.filter(_.identity)
.value();
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>
Try this.
const array = _(resp.data)
.omit(_.isUndefined)
.flatMap('building')
.map()
.omit(_.isUndefined)
.value()
I can't figure out what I'm doing wrong when accessing this JSON object:
{ Items:
[ { mId: 'who' },
{ mId: 'am' },
{ mId: 'I' } ],
Count: 3,
ScannedCount: 3 }
{ Items:
[ { cId: 'big' },
{ cId: 'scary' },
{ cId: 'muppet' } ],
Count: 3,
ScannedCount: 3 }
This is the object I am getting back from a function and I'm trying to access the individual items to update their values.
When I want to print 'who' for example, I do this:
console.log(obj.Items[0].mId)
Now I expect to get 'who' back, but this is what prints:
undefined
who
That 'undefined' always tags along. What am I doing wrong here?
Also, if I try to change the value somewhere by doing:
obj.Items[0].mId = 'x'
This happens:
{ Items:
[ { mId: 'x' },
{ mId: 'am' },
{ mId: 'I' } ],
Count: 3,
ScannedCount: 3 }
{ Items:
[ { cId: 'big', mId: 'x' },
{ cId: 'scary' },
{ cId: 'muppet' } ],
Count: 3,
ScannedCount: 3 }
This is not what I want.. I don't understand how to access only the first 'Items'. It seems like I'm accessing both.
Any help or advice is greatly appreciated. I probably don't need to say that I'm not very used to working with JSON.
For the undefined issue, please see the answer here: What does it mean if console.log(4) outputs undefined in Chrome Console? but TL;DR you're just seeing the 'undefined' return from console.log(), because it has no return value. It shouldn't be an issue once you're not working in the console.
As for how you have 2 separate objects both called obj, I don't understand, as other said in the comments, please post the full code so we can see how this is being used/generated.
Also for clarification it looks like you're working with JavaScript objects, not JSON, similar but not the same.
In my React Native application I am using the RNDBModels package that is a wrapper over AsyncStorage. Currently I am saving a JSON object through RNDBModels and that works correctly, however accessing the data is proving challenging.
When the code is return from the get method, it is return inside a JSON Object and I would essentially like the values from the result, so that I can iterate over it for a list.
The returned result:
{
'1':
{
name: 'Galaxy',
description: '20gram bars',
_id: 1
},
'2':
{
name: 'Snickers',
description: 'Hazelnuts',
count: 2,
_id: 2
}
}
And the desired outcome so that I can easily iterate over the objects in the array and then render a list in React Native.
[
{
name: 'Galaxy',
description: '20gram bars',
_id: 1
},
{
name: 'Snickers',
description: 'Hazelnuts',
count: 2,
_id: 2
}
]
Any suggestions at accessing the values? I have tried using Object.keys and then subsequently Object.values to no avail sadly.
You can do it with the in operator :
const data = {
'1': {
name: 'Galaxy',
description: '20gram bars',
_id: 1
},
'2': {
name: 'Snickers',
description: 'Hazelnuts',
count: 2,
_id: 2
}
};
var array = [];
for (let prop in data) {
array.push(data[prop]);
}
console.log(array);
JSFiddle
If you're using lodash just one line of code would work for your purpose
_.values(YOUR_OBJECT);
https://lodash.com/docs#values
It will make an array of values from your object.
Im trying to merge 2 data sources in 1, I wanna loop through them and if a specefic value matches than add it to the first object with the same value and add the in the emty array what is already there. No matter how much objects I have.
So lets say I have this information
Source 1
one = {
"teams": [
{
name: 'ABC',
members: [],
rooms: '0'
},
{
name: 'DEF',
members: [],
rooms: '1'
}
]
}
Source 2
two = {
"persons": [
{
name: 'Foo',
gender: 'male',
room: '1'
},
{
name: 'Bar',
gender: 'female',
room: '2'
}
]
}
And what I want is that the 'persons' array merge to the members array if the 'room and rooms' value matches.
What I would assume is something similar like this:
for(var i = 0 ; i < two.persons.length; i++) {
if (one.teams[i].rooms == two.persons[i].room) {
data.teams[i].members.push(two.persons[i]);
}
}
using higher order methods you can do:
one = {
"teams": [
{
name: 'ABC',
members: [],
rooms: '0'
},
{
name: 'DEF',
members: [],
rooms: '1'
}
]
};
two = {
"persons": [
{
name: 'Foo',
gender: 'male',
room: '1'
},
{
name: 'Bar',
gender: 'female',
room: '2'
}
]
};
var ttt = one.teams.map(function(x){
var roomVal= x.rooms;
x.members = two.persons.filter(function(t){
return t.room == roomVal});
return x;
})
one.teams = ttt;
console.log(one)
The problem with your code is that once you iterate the two array, then you do not go back and see if the previous element matched with the current one.
For example, if [0] on each arrays does not match and you iterate to index [1] in the for-loop, you do not have a way to check if two[1] matched one[0].
To do a complete search, you could directly iterate the arrays for each value of two:
two.persons.forEach(function(person) {
one.teams.forEach(function(team) {
if (team.rooms == person.room) {
team.members.push(person);
}
});
});
There are many strategies to do this. But most important you should iterate each array separately. I would use an Array.forEach();
one.teams.forEach(function (team, teamsIndex, teamsArray) {
two.persons.forEach(function (person, personsIndex, personsArray) {
if (team.room == person.room) {
// Do what you need to do.
}
});
});
Didn't check syntax so be aware to read Array.forEach(); documentation.