JavaScript. Extract values from associative array - javascript

How can I get the values from this associative array in JavaScript?
I just need the email addresses and not the labels.
(
{
office = ("my#email.com");
home = ("ahome#anotheremail.com");
work = ("nothing#email.com");
},
{
home = ("test#test.se");
}
)
UPDATE: Prefered output in JSON would be:
{
"data": [
{
"email": "my#email.com"
},
{
"email": "ahome#anotheremail.com"
},
{
"email": "nothing#email.com"
},
{
"email": "test#test.se"
}
]
}
Thankful for all input!

What you probably meant to do is:
var x = [{
office: ("my#email.com"),
home: ("ahome#anotheremail.com"),
work: ("nothing#email.com")
},
{
home: ("test#test.se")
}]
and:
for(var j = 0; j < x.length; j++)
{
for(var anItem in x[j])
{
console.log(x[j][anItem])
}
}
// EDIT:
however, it's not the best practice to use for … in.
Maybe you could change your data structure to:
var x = [[{
value: "my#email.com",
type: "office"
},
{
value: "ahome#anotheremail.com",
type: "home"
},
{
value: "nothing#email.com",
type: "work"
}],
[{
value: "test#test.se",
type: "home"
}]];
and iterate over using:
for( var i = 0, xlength = x.length; i < xlength; i++ )
{
for( var j=0, ylength = x[i].length; j < ylength; j++ )
{
console.log(x[i][j].value);
}
}

Here's a one-liner:
console.log(Object.keys(assoc).map(k => assoc[k]));
where assoc is your associative array.
Edit
I have a better answer here.

You can 'foreach' over the object to get it's properties:
for(var j = 0; j < mySet.length; j++)
{
for(var propName in mySet[j])
{
var emailAddress = mySet[j][propName];
// Do Stuff
}
}

Answer for edited question:
var ret = {data: []};
for(var j = 0; j < x.length; j++)
{
for(var anItem in x[j])
{
ret.data.push({
email: x[j][anItem]
});
}
}
console.log(ret);
The result is kept in ret.

Is it your input in JSON format? Because if so, it's the wrong syntax. However
let _in = [
{
office : "my#email.com",
home : "ahome#anotheremail.com",
work : "nothing#email.com",
},
{
home : "test#test.se"
}
]
let _out = []
_in.forEach( record => {
_out = _out.concat(Object.values(record).map(x => new Object({email : x})))
})
console.log(_out)
for each record I extracted values and "packed" into an object with the "email" attrbiute, then I merged all those arrays obtained from the original array of records

It seems that you're looking for Object.values.

Related

Failed to console unique names from JSON array

I have a JSON array having hundreds of objects where each JSON object having name and hobbies property.
Below is the JSON structure:
const data = [
{
name:'Paul',
hobbies: ['Football','Reading']
},
{
name:'Riya',
hobbies: ['Singing','Dancing']
},
{
name:'Jack',
hobbies: ['Gaming']
}
]
So here if I will iterate through this data it will give me same name multiple times wherever multiple hobbies are present.So if I am console it result would be
Paul,Football
Paul,Reading
Riya,Singing
Riya,Dancing
Jack,Gaming
I don't want above output I want wherever there is same name is coming in a same object don't console it like below:
Paul,Football
"",Reading
Riya,Singing
"",Dancing
Jack,Gaming
Below is my code:
const data = [
{
name:'Paul',
hobbies: ['Football','Reading']
},
{
name:'Riya',
hobbies: ['Singing','Dancing']
},
{
name:'Jack',
hobbies: ['Gaming']
}
]
const example = (data) => {
for(var i=0;i<data.length;i++){
for(var j=0;j<data[i].hobbies.length;j++){
console.log(data[i].name,data[i].hobbies[j]);
if(i=0){
console.log(data[i].name,data[i].reports[j]);
}
else{
const prev = i-1;
if(data[prev].name == data[i].name) { //Getting TypeError here cannot read property 'name' of undefined
console.log("",data[i].reports[j]);
}
else{
console.log(data[i].name,data[i].reports[j]);
}
}
}
}
}
example(data);
In above code I am trying to compare the previous value of name in data array with the current value of name. If it's same then making name field " " else putting name value and for first element for position 0 I am putting value as it is.
Why am I getting this TypeError?
There are several issues, first is typo, you assigned instead of comparing
if (i=0) {
// ^^^^^
console.log(data[i].name,data[i].reports[j]);
}
The rest is logic, all you have to do is to check the index of j
const example = data => {
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].hobbies.length; j++) {
if (j == 0) {
console.log(data[i].name, data[i].hobbies[j])
} else {
console.log("", data[i].hobbies[j])
}
}
}
}
Full solution
const data = [
{
name: "Paul",
hobbies: ["Football", "Reading"],
},
{
name: "Riya",
hobbies: ["Singing", "Dancing"],
},
{
name: "Jack",
hobbies: ["Gaming"],
},
]
const example = data => {
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].hobbies.length; j++) {
if (j == 0) {
console.log(data[i].name, data[i].hobbies[j])
} else {
console.log("", data[i].hobbies[j])
}
}
}
}
example(data)
const data = [
{
name:'Paul',
hobbies: ['Football','Reading']
},
{
name:'Riya',
hobbies: ['Singing','Dancing']
},
{
name:'Jack',
hobbies: ['Gaming']
}
]
data.forEach(d => {
d.hobbies.forEach((hobby, index) => {
const name = index == 0 ? d.name : '""'
console.log(name + ',' + hobby)
})
})
Just print the name if index of hobby is 0

How can I delete all objects in a json array by its keyword

I have json like this:
json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
},
]
What I need is to delete value2 so the json would look like:
json = [
{
"value1":"3863"
},
{
"value1":"4456"
},
{
"value1":"98494"
},
]
I have tried to use
for(var i = 0; i < json.length; i++)
{
delete json["value2"];
}
but it doesn´t work.
Is there any way of doing that ?
const json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
},
];
json.forEach(item => delete item.value2);
use map.
json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
}
];
console.log(json.map(({value1}) => ({value1})));
With your current syntax:
for(var i = 0; i < json.length; i++)
{
delete json[i].value2;
}
You just have missed i usage in accessing json array elements:
for(var i = 0; i < js.length; i++)
{
delete json[i]["value2"];
}
You forgot the iterator i:
delete json[i]["value2"];
var json = [
{
"value1":"3863",
"value2":"4567"
},
{
"value1":"4456",
"value2":"87687"
},
{
"value1":"98494",
"value2":"4534"
},
];
for(var i = 0; i < json.length; i++) {
delete json[i]["value2"];
}
console.log(json);

array.push to an array within an array

I'm trying to push JSON data to an array within an array. The problematic difference to other examples of this I can find is that both arrays are being built by a loop which I believe is the reason for the error I'm receiving. TypeError: Cannot call method 'push' of undefined
Here's a somewhat minimal example of what I'm trying to achieve.
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var departure = data.trips[i].dep.time;
var arrival = data.trips[i].arr.time;
json.trips.push({departure: departure, arrival: arrival, nodes: []});
for (var j = 0; j < data.trips[i].legs.length; j++) {
json.trips.nodes.push({test: 'test'});
}
}
The output I'm trying to create should be looking like this.
{
origin: origin,
destination: destination,
trips: [
{
departure: departure,
arrival: arrival,
nodes: [
{test: test},
{test: test},
{test: test}
]
},
{
departure: departure,
arrival: arrival,
nodes: [
{test: test},
{test: test},
{test: test}
]
}
]
}
The test nodes are nonsensical, sure, but shouldn't adding them in this way be possible?
The line:
json.trips.nodes.push({test: 'test'});
should be:
json.trips[i].nodes.push({test: 'test'});
json.trips.nodes is indeed undefined. I believe you want to add it to the new item in the trip loop?
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var newNode = {
departure: data.trips[i].dep.time,
arrival: data.trips[i].arr.time,
nodes: []
};
for (var j = 0; j < data.trips[i].legs.length; j++) {
newNode.nodes.push({test: 'test'});
}
json.trips.push(newNode);
}
var json = {origin: data.origin.name, destination: data.destination.name, trips: []};
for (var i = 0; i < data.trips.length; i++) {
var departure = data.trips[i].dep.time;
var arrival = data.trips[i].arr.time;
var trip = {departure: departure, arrival: arrival, nodes: []}
for (var j = 0; j < data.trips[i].legs.length; j++) {
trip.nodes.push({test: 'test'});
}
json.trips.push(trip);
}

Javascript array format for charts

I have two arrays
A =[1990,1991,....]
B=[a,b,c,d,e,f,...]
I want the resultant array in this format
Resultant=[{
name: 1990,
data: [a,b,c]
},{
name: 1991,
data: [d,e,f]
},...
]
Please help me how will I make it using for loops?
How about this:
var b= ["a","b","c","d","e","f"];
var result = [1990,1991].map(function(n){ return { name:n, data: b.splice(0,3)} });
This will format data with Array.prototype.map, based on your (rather vague) requirement:
var A = [1990,1991];
var B = ["a","b","c","d","e","f"];
var formatted = A.map(function (name, i) {
return {
name: name,
data: B.slice(i*3, i*3+3)
}
});
/*[
{
"name": 1990,
"data": [
"a",
"b",
"c"
]
},
{
"name": 1991,
"data": [
"d",
"e",
"f"
]
}
]*/
Assuming that for each in A, you want data to store 3 elements of B. I've stuck with your requirement of using for loops.
var Resultant = [];
for (var i = 0; i < a.length; i++) {
var data = [];
for (var j = 0; j < 3, B.length > 0; j++) {
data.push(B.shift());
}
Resultant.push({name: A[i], 'data': data});
}
This worked for me:
http://jsfiddle.net/s5zdD/ <-- see jsfiddle to show
A =[1990,1991,1992];
B=['a','b','c','d','e','f','g','h','i'];
var Resultant = jQuery.map(A, function(i,v){
// if no jQuery use:
// var Resultant = A.map(function(i,v){
return {
'name':A[v],
'data': B.splice(0,3)
}
})
console.log(Resultant);

Build JSON Object from string containing multi-dimensional

I have an array of name/value objects (below). The names are formatted to represent multi-dimensional array.
I need to build a full JavaScript object out of it(bottom).
[{
name: "getQuote[origin]",
value: "Omaha,NE"
},
{
name: "getQuote[destination]",
value: "10005"
},
{
name: "getQuote[country]",
value: "us"
},
{
name: "getQuote[vehicles][0][year]",
value: "1989"
},
{
name: "getQuote[vehicles][0][make]",
value: "Daihatsu"
},
{
name: "getQuote[vehicles][0][model]",
value: "Charade"
},
{
name: "getQuote[vehicles][0][count]",
value: "1"
}]
Into something like this:
{getQuote :
{ origin : Omaha},
{ destination : 10005},
{vehicles : [
{
year : 1989,
make: Honda,
model : accord
},
{
//etc
}]
n
You can do it manually, like this:
var source = [ /* Your source array here */ ];
var dest = {};
for(var i = 0; i < source.length; i++)
{
var value = source[i].value;
var path = source[i].name.split(/[\[\]]+/);
var curItem = dest;
for(var j = 0; j < path.length - 2; j++)
{
if(!(path[j] in curItem))
{
curItem[path[j]] = {};
}
curItem = curItem[path[j]];
}
curItem[path[j]] = value;
}
dest is the resulting object.
Check it working here: http://jsfiddle.net/pnkDk/7/

Categories

Resources