Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Playing with nodeJs currently and have been trying to write new data into an existing JSON file, only to have problems with the format as well as getting the right data in. I want to get this new JSON obj to the FIRST of the array list. I did this by grabbing the first index ID, increment it, and tried using unshift() but it isn't adding the way I expected.
JSON file content data.json:
[
{
"id": 3,
"content": "three"
},
{
"id": 2,
"content": "two"
},
{
"id": 1,
"content": "one"
}
]
Code I wrote for new JSON obj I want to add:
var allJSON = fs.readFileSync('data.json');
var allj = JSON.parse(allJSON);
var lastId = parseInt(allj[0].id);
var newData = {
id: ++lastId,
content: "test"
};
var allNewJSON = allj.unshift(JSON.stringify(newData));
// this yields a result of just the number "4" and erased everything else.
Array#unshift does not create and return a new array; instead, it modifies the original array and returns its new length. In your case, this value would be 4. I would suggest ignoring the return value of unshift and simply continuing your code using the allj variable, like so:
var allJSON = fs.readFileSync('data.json');
var allj = JSON.parse(allJSON);
var lastId = parseInt(allj[0].id);
var newData = {
id: ++lastId,
content: "test"
};
allj.unshift(newData);
console.log(allj) // modified as desired!
Edit: As was mentioned in the comments above, you probably don't want to be calling JSON.stringify on the object newData before inserting it into your array. At this point you want to be working with JS objects rather than JSON strings.
Your result is due to the way unshift works.
unshift is a function which returns the length of the updated array.
For example
> const a = [10, 20, 30];
> a.unshift(5);
4
That's right, the call to unshift returns 4, because the updated array has 4 elements.
Let's see the updated value of a:
> a
[5, 10, 20, 30]
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have got an issue with the Array.map function not working as I would expect. I have simplified my example below, I just want to get an understanding of where I am going wrong.
So I have the following code below:
console.log(this.reportTestData)
let data = this.reportTestData.map((row) => {
return [ 1 , 2, 3]
});
console.log(data)
return data
From the first console.log, this.reportTestData is an array containing 92 objects, the content of each object is irrelevant:
So from the code, I would expect the map function to run over the array 92 times, and return a new array ( [1,2,3] ) for each element. Leaving me with an array of 92 elements, which each element is a [1,2,3] array. However that is not what I get.
Instead I am getting an array of 92 elements, but each element is completely empty.
I also tried to return objects from the map function instead:
console.log(this.reportTestData)
let data = this.reportTestData.map((col) => {
return { test : 1 }
});
console.log(data)
return data
However I still get empty objects returned with no properties:
Any help that could be offered would be greatly appreciated, as I cannot see where I am making a mistake.
I tried for 10 items in an array, and as you may see there are 10-pieces of [1,2,3] ... so map function is working fine, as par I can say.
let reportTestData = [1,2,3,4,5,6,7,8,9,10]
console.log(reportTestData)
let data = reportTestData.map((item) => [ 1 , 2, 3]);
console.log(data)
Now trying again with 10-objects in an array:
let reportTestData = [{},{},{},{},{},{},{},{},{},{}]
console.log(reportTestData)
let data = reportTestData.map((item) => [ 1 , 2, 3]);
console.log(data)
Again map function of Arrays works fine, so you need to check what wrong you are doing in your code.
Works for me
const reportTestData = new Array(12).fill(0);
let data1 = reportTestData.map((row) => {
return [ 1 , 2, 3]
});
console.log(data1)
let data2 = reportTestData.map((row) => {
return { test : 1 }
});
console.log(data2)
I have a headless CMC WP that's fetched into my Javascript and stored. I want to filter it by a property(if the property value = to the value I input in html then it should append to the innerHTML) and therefore I tried to loop through it but it does not work.
This is my function:
for (let i in this.filtered) {
for (let y in this.filtered[i].categories) {
//console.log(this.filtered[i].categories[y] + " ");
const results = this.filtered[i].categories[y].filter(post => post == value)
console.log(results);
}
}
It says in the console that this.filtered[i].categories[y].filter is not a function.
this is a part of the array from this.filtered, I want to filter by categories.
This is what it shows when I console.log(this.filtered[i].categories[y]);
Thank you in advance!
It says in the console that this.filtered[i].categories[y].filter is not a function.
The items in the categories array, according to your screenshot, are simple integers. Integers don’t understand/implement any method called filter(). (Put another way: what would you do if I told you to filter the number 7?) Logically, it’s clear that this is not what you intended.
While you’re headed down the right path, I’d recommend you keep it simple: run Array.filter on your outermost array and use the logic in the callback to test whether the categories sub-array contains the value you’re looking for:
var _this = {};
_this.filtered = [{
acf: {},
author: 1,
categories: [18, 2, 3]
},
{
acf: {},
author: 2,
categories: [4, 3, 7, 18]
}
];
const value = 2;
var filteredResults = _this.filtered.filter(cv => cv.categories.includes(value));
console.log(filteredResults);
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 4 years ago.
I posted about this before trying to use a regular expression, but this time is a bit different.
So I have this list of 500 phone numbers. Here is a little sample of them:
{
8664665844
8885444636
8664604776
8776434327
8887441938
8882642882
8888097429
8668943258
8777711234
8669894327
}
It looks a bit different, this is on my mongoDB server, so its more like an array of objects with a unique uid... so for example:
[
{
_id: kasjf234lkj109euf9023u4n,
field1: 8669894327,
}
]
something like that right.
So basically, my webapp is using a csv file of numbers that you want to compare to your base numbers.
My first thought was using a for, while, for loop kind of thing but im not sure how well it'll work:
for(var i = 0; i < basenums.length; i++){
while ( i >= 0 ){
for(var j = 0; j < comparing.length; j++){
if comparing[j] == basenums.field1[i]{
push that number to a 'dupes' array
}else{
break or something?
}
}
}
}
...this logic is starting to hurt my head...
I know theres an 'includes()' method, but I havn't really used it and when I tried it in this case, It gave me everything as false, even tho the list I was using to compare is just a copy of my 'basenums' list on my server.
What would be the more 'correct' way of doing this?
I'm trying to compare an array with an array. Not a value in its specific array to its own array.
So, rather than marking this as a duplicate, maybe you should re-read:
I have 2 arrays of numbers: [1, 2, 3, 4, 5, 6] and [1, 2, 3, 4, 5, 6] How do I take array a index 0 and compare it to array b every index, then take index 1 of array a and compare to every index in array b, so on and so forth until i > arrayA.length.
Don't try to do everything in one single step. Break your problem into smaller chunks:
Format mongo's response into a hash map that you can efficiently query (O(1))
Test each input number against this map
Step 1:
var hashmap = {}
basenums.forEach(function(basenum) {
hashmap[basenum.field1] = true;
})
Step 2:
var dupes = [];
comparing.forEach(function(comparingNum) {
if(hashmap[comparingNum]) {
dupes.push(comparingNum);
}
})
EDIT: I am not sure, whether you want to have your dupes as a set (unique array). If so, you could use an alternate Step 2:
var dupesMap = {};
comparing.forEach(function(comparingNum) {
if(hashmap[comparingNum]) {
dupesMap[comparingNum] = true;
}
})
var dupes = Object.keys(dupesMap);
You can push values into an array and create a new set with the array. Sets do not keep redundant elements in them. Try this;
let a = ["a","b","a","b","a","b","a","b","a","c"];
console.log(a);
let uniqueA = [...new Set(a)];
console.log(uniqueA);
By the way, for piece of code I got a help from this page: https://medium.com/front-end-hacking/getting-unique-values-in-javascript-arrays-17063080f836
I have an enum of different Steps
export enum StepCategory {
START = 0,
POSITION_1 = 1,
TRANSPORT = 2,
RECEIVER = 3,
END = 4,
NO_STEP_MATCH = 5
}
This will later result in an array, where for every Step I have an object. The Problem is I won't load all the information at once, so i can'tdo a simple for-loop and push each item chronogically. I could be that I first load the value for Step 4, so my array would be:
var array = [{"END" , "POSITIVE"}]
Afterwards I would get the Info for Step 2, then I would have:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
But this is not sorted.
What should I do? Should I declare an array of 6 undefined values
var array = [undefined, undefined, undefined, undefined, undefined, undefined]
This way I wouldn't need any sorting-algorithm after each Update, and can just push the value at the right position.
Just some small Info: I use AngularJS 1, Typescript and Lodash
In plain Javascript, you could sort it with an object and the assigned values of the key.
var StepCategory = { START: 0, POSITION_1: 1, TRANSPORT: 2, RECEIVER: 3, END: 4, NO_STEP_MATCH: 5 },
array = [["END", "POSITIVE"], ["TRANSPORT", "POSITIVE"]];
array.sort(function (a, b) {
return StepCategory[a[0]] - StepCategory[b[0]];
});
console.log(array)
First of all, this is - as someone mentioned in the comments - not syntactically correct:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
I assume that this was just a typo writing this question. Additionally if you actually use the enum in your array as key and just left it out for demonstration purposes, I would expect your array of objects to look something like this:
var array = [{StepCategory.END: "POSITIVE"}, {StepCategory.TRANSPORT: "POSITIVE"}]
In order to sort this with LoDash you could use something like this:
var sortedArray = _.sortBy(array, i => Object.keys(i)[0]);
This sorts your array by the value of the first key of each object which refers to your enum value.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
Supposed to have an array of objects of objects like
[
{
"key_set1": {
int_val: 3,
arr_val: [
1,
3,
4
]
}
},
{
"key_set2": {
string_val: "foo"
}
}
]
I want to flatten inner objects keys to a new root object to get at the end
{
"key_set1": {
"int_val": 3,
"arr_val": [
1,
3,
4
]
},
"key_set2": {
"string_val": "foo"
}
}
Assumed that
This nested structure can have N levels with N > 10
The structure is a valid json object not a javascript object i.e. it has atomit/non atomic types, not function object types;
The whole input json file can be hundreds of KBytes;
The work must be done in JavaScript V8 / ECMAScript6;
The processing time must be of order of milliseconds
A variant of this mapping, needs to parse the input json object and modify the values (like using map array method).
I want to get the most optimized solution for this using built-in methods like forEach and/or fast iterators for, while etc., for the best/worst cases.
As long as I understand it correctly, you like to replace the array with an object and take the first level key as the new key for the result object.
var array = [{ "key_set1": { int_val: 3, arr_val: [1, 3, 4] } }, { "key_set2": { string_val: "foo" } }],
object = {};
array.forEach(function (a) {
var key = Object.keys(a)[0];
object[key] = a[key];
});
console.log(object);
If you "want to get this optimized at its best" - you shouldn't use Array.map in your case as it returns a new array. You just need to iterate fast through the list array and fill the new flattened object. Consider the following "optimized" solution:
var flattened = {}, len = list.length;
while (len--) {
Object.keys(list[len]).forEach((k) => (flattened[k] = list[len][k]));
}
console.log(JSON.stringify(flattened, 0, 4));
The output:
{
"key_set2": {
"string_val": "foo"
},
"key_set1": {
"int_val": 3,
"arr_val": [
1,
3,
4
]
}
}