value extraction from array in javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
business=[0:{"name":{"en":'prateek'}},1:{"name":{"ar":'rahul'}}]
How I can extract the value of en and ar from this type of the repeted object in a array

The issue with your question is that you define business as an Array with the use of square brackets, but then proceed to use key value pairs directly within the array (via the usage ":"), which is reserved for objects and not arrays. I'd recommend researching both array and object datatypes, however simply put:
let myArray = [1, 2, 3, ...];
// only stores values which can be retrieved using the values index i.e. myArray[0]
let myObj = {"key1" : "value1", "key2" : "value2"};
// values are stored against keys, and can be accessed via the key i.e. myObj.key1

I think you've confused how objects and arrays should work. My guess is that you'd be better off with this structure:
let businesses = [];
businesses.push({enName: 'prateek', arName: 'rahul'});
console.log(businesses[0], businesses[0].enName, businesses[0].arName);
This way you're using an array to hold a collection of businesses and which are represented by objects. These objects in turn have attributes for enName and arName.
I think this would be a much clearer way of structuring your issue.

Related

How to get data in object without looping [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want to get data from the object without for loop
this is my object
data = [{name:"A",value:[java:45,c++:50]},{name:"B",value:[java:12,c++:47]},{name:"C",value:[java:15,c++:32]}]
Expected result:
result_name = ["A","B","C"]
result_java = [45,12,15]
The structure of your array data is invalid. You wrote nested array value in square brackets yet the items are written as key-value pairs.
There is no magical way you can obtain multiple data from an array without iteration/looping. (unless you already know the indices, but this defeats the purpose of using arrays)
That said, if you meant to avoid only the "for" loops, you can:
Fix your data as below.
let data = [
{name:"A", value:{java:45,"c++":50}},
{name:"B", value:{java:12,"c++":47}},
{name:"C", value:{java:15,"c++":32}}
];
Run an alternative loop such as below.
console.log(data.map(item => item.name)); // ["A", "B", "C"]
console.log(data.map(item => item.value.java)); // [45,12,15]

Pushing data to an array inside another array with Javascript [closed]

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 4 years ago.
Improve this question
I made an array for a raffle system using node.js and discord.js which has this data set.
[{"author":"Name","rafflename":"RAFFLE","amount":"10","entries":"[]"}]
When someone tries to enter the raffle I'd like to make another JSON array inside the entries tag.
The problem i face is when i use raffles[0].entries.push({ 'username': 'example', 'user_id': '1' });
It returns an error: raffles[0].entries.push is not a function
I assume this is because it is looking for the array raffles[0].entries.push which does not exist. But I've only ever used the push command. So I am not sure how to fix this issue.
Move your entries [] out of double quotes, i.e. Use "entries" :[]
You are trying to push to a string instead of array
You have to cast entries to Array first.
const raffles = [{"author":"Name","rafflename":"RAFFLE","amount":"10","entries":"[]"}]
// cast entries to Array
raffles[0].entries = JSON.parse(raffles[0].entries)
// now you can push them
raffles[0].entries.push('test')
console.log(raffles)
It isn't working because you have "" around the properties inside of your object. you can fix this by either removing the "" or doing this:
raffles[0]['entries'].push(//your code here);
When properties of an object are strings (i.e. when they have quotes around them) you must access that property using "dot notation"
eg:
var object = {"property":"five"};
console.log(object["property"]); //prints 'five'
console.log(object.property); //throws an error
Format Your Array according to #Bibberty Comment and do operation
raffles=rafale=[{"author":"Name","rafflename":"RAFFLE","amount":10,"entries":[]}]
raffles[0].entries.push({ 'username': 'example', 'user_id': 1 });
console.log(raffles)

iterate over formatted JSON Array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am querying an MS SQL Database, which is returning a formatted JSON Array. Below is an example of what is returned. I have used just about every JavaScript example I can find to iterate over the array, but nothing is working:
[
[
{"id":1,"Title":"Friday"},
{"id":2,"Title":"Saturday"},
{"id":3,"Title":"Sunday"}
]
]
There are two issues with your json array there that will need to be solved first
You have a " missing on Sunday
You have an array of arrays, not just an array.
When your array is correct the return from your SQL should look like this:
'[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]'
That isn't a json object yet, it's just a string that looks like one, to make use of that as a json object/array you need to parse it like this:
var jsonArray = JSON.parse('[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]');
If you can't get around the [[]] array within an array, you can handle it like this:
var jsonOuterArray = JSON.parse('[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"},{"id":3,"Title":"Sunday"}]]');
var jsonArray = jsonOuterArray[0];
With that there are many ways to iterate over it in javascript, it all depends what libraries you use and what you want to get out of it, like how the jQuery example give not only the object but the position in the array for that object but the forEach will not.
For each example, jsonArray will be the parsed out json from your SQL, key will be the position in the array and value will be the object in the array.
JavaScript: (array prototype forEach)
jsonArray.forEach(function(value){
console.log(value.id, value.Title)
});
JavaScript: (for loop)
for (var key = 0; key < jsonArray.length; key++) {
var value = jsonArray[key];
console.log(value.id, value.Title)
};
jQuery:
$.each(jsonArray, function (key, value){
console.log(value.id, value.Title)
});
Using nodejs (ES5 syntax) :
> [[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":"Sunday"}]][0]
.forEach(function(elt){ console.log(elt.id, elt.Title)})
1 'Friday'
2 'Saturday'
3 'Sunday'
Note that a quote is missing before Sunday:
[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":Sunday"}]]
therefore you will not be able to evaluate this JSON. Assuming that the JSON is corrected to
[[{"id":1,"Title":"Friday"},{"id":2,"Title":"Saturday"}, {"id":3,"Title":"Sunday"}]]
you will be able to iterate it in conventional manners, using a for cycle, for example.

What is the best way to group data pairs in javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Instead of using associative arrays (objects), what is the best way to associate two values so they are always associated and can both be accessed as separate values? Associative arrays are annoying because their order isn't guaranteed and you can't access them using indexes.
I could create two separate arrays but if I randomize their order for display their association would not match, and if they are separate in code there is a good chance I can make a mistake when recording their values, putting them in the wrong order so they don't perfectly match up.
In Javascript you can use multidimensional arrays:
var data = [
[1, 2],
[3, 4]
];
data[0][0]; // get '1'
data[0][1]; // get '2'
Also if you need to associate data in a more abstract way, ES6 has WeakMaps:
var wm = new WeakMap();
var x = document.createElement("div");
wm.set(x, {foo: 1, bar: 7});
console.log(wm.get(x).bar) // get '7' from object you associated to HTMLElement
I do not now which kind of data you should store but maybe you could try to store data in a single variable in this way:
var data = [];
data[0] = "Test" + "|" + Value;

Get list of items in one list that are not in another [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have two comma separated lists, the first is a list of possible values, and the second is a list of "selected" values. I need to create a list of all of the items in the first list that do not exists in the second list.
I could just split the first list into an array and use a "for" to go through the list using a string_pos to see if the first list item is contained in the second, but I'm wondering if there is a more efficient way to accomplish this.
Thanks!!
You can filter the possible list.
if the lists are strings, split or match them to get arrays.
var possible=[1,2,3,4],
selected=[2,4];
var unchosen=possible.filter(function(itm){
return selected.indexOf(itm)==-1;
});
unchosen
/* returned value: (Array)
1,3
*/
If you are looking for the best possible way, this is what you have to do
Convert the list to be checked, to an object, in liner time. Because, objects are technically hashtables, which offer faster lookups O(1)).
Then, iterate over the first list and check if the current element is there in the object or not. If it is not there, add it to the result.
var list1 = [1, 2, 3], list2 = [1, 2], dict2 = {};
list2.forEach(function(item) {
dict2[item] = true;
});
var result = list1.reduce(function(prev, current) {
if (dict2.hasOwnProperty(current) === false) {
prev.push(current);
}
return prev;
}, [])
console.log(result);
Output
[ 3 ]
The first thing you want to do is definitely to split the two comma separated lists into arrays of strings. Assume that they are formatted fairly reasonably, you can do this with
possible_values = possible_string.split(/,\s?/) //split on commas with a possible space
selected_values = selected_string.split(/,\s?/)
If you are willing to use outside libraries, underscore.js has a perfect function for this. The operation you are describing is the set difference operator, which is the difference function in underscore.
The result you want is the return value of calling
_.difference(possible_values, selected_values)

Categories

Resources