Making new array and push there keys on that new array [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 4 years ago.
Improve this question
I have a list of an object array
var list = {
Achievement: ["110", "100", "104", "110"],
Emp Code : ["1000001", "1000001", "1000001", "1000001"],
Product :["Product A ", "Product B", "Product A ", "Product B"],
Reportee Name :["Harry", "Harry", "Peter", "Peter"],
Target : ["116", "94", "105", "114"],
percentage: ["94.82758621", "106.3829787", "99.04761905", "96.49122807"]
}
and the array I want that is mention below. Where key item should be the part of array.
var list = {
0: ["Achievement","110", "100", "104", "110"],
1 : ["Emp Code","1000001", "1000001", "1000001", "1000001"],
2 :["Product" ,"Product A ", "Product B", "Product A ", "Product B"],
3 :["Reportee Name","Harry", "Harry", "Peter", "Peter"],
4 : ["Target","116", "94", "105", "114"],
5: ["percentage","94.82758621", "106.3829787", "99.04761905", "96.49122807"]
}

You can use Object.keys() and .reduce() method:
let data = {'Achievement': ["110", "100", "104", "110"],'Emp Code' : ["1000001", "1000001", "1000001", "1000001"],'Product' :["Product A ", "Product B", "Product A ", "Product B"],'Reportee Name' :["Harry", "Harry", "Peter", "Peter"],'Target' : ["116", "94", "105", "114"],'percentage': ["94.82758621", "106.3829787", "99.04761905", "96.49122807"]};
let result = Object.keys(data)
.reduce((a, c, i) => (a[i] = [c, ...data[c]], a), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Why do you need an object with indexes like an array? Array solution:
let list = {'Achievement': ["110", "100", "104", "110"],'Emp Code' : ["1000001", "1000001", "1000001", "1000001"],'Product' :["Product A ", "Product B", "Product A ", "Product B"],'Reportee Name' :["Harry", "Harry", "Peter", "Peter"],'Target' : ["116", "94", "105", "114"],'percentage': ["94.82758621", "106.3829787", "99.04761905", "96.49122807"]};
let result = []
for (let key in list) {
result.push([key, ...list[key]])
}
console.log(result)

Related

Javascript, filtering on object in comparison to array

I'm still learning and I had a question the other day filtering two arrays, which helped a lot for my understanding!
However now, I have a new issue as the complexity has grown a bit from being two simple arrays! Now instead, I have a array with multiple objects named animals which categorizes animals based whether they are housepets, insects or wild animals and each contains a object with their characteristics. Now I want to compare this on a simple array seen below.
Array with Object
let animals = [
{
"housePets" : [ { "name": "Cat", "food" : "Fish", "description": "Long tail, sharp claws" }, { "name": "Dog", "food" : "Biscuits", "description" : "Humans best friend" } ]
},
{
"wildAnimals" : [ { "name": "Giraffe", "food" : "Leafes", "description" : "A very long neck" }, { "name": "Lion", "food" : "Meat", "description" : "Featured in Lion King" } ]
},
{
"insects" : [ { "name": "Ladybug", "food" : "Leafes", "description" : "Red and black" }, { "name": "Spider", "food" : "Flies", "description" : "From the friendly neighbourhood" } ]
}]
Arr:
let animalsArr2 = [housePets]
I'm having a bit of trouble fully understanding on how to work with this JSON format in general. The biggest struggle for me is targeting the specific array like wildAnimals.
For example, one thing I want to do is filter the animals array based on what's inside animalsArr2 and pick a random one from the animalsarr that's not featured in animalsArr2 like "wildAnimals" and "Insects". I hope someone can give me some ideas on how to tackle this issue or if it can be tackled in a easier way.
You can use the .find() array method to return the list that you want. For example if you want to return the wild animals list:
let animals = [
{
"housePets" : [
{ "name": "Cat", "food" : "Fish", "description": "Long tail, sharp claws" },
{ "name": "Dog", "food" : "Biscuits", "description" : "Humans best friend" }
]
},
{
"wildAnimals" : [
{ "name": "Giraffe", "food" : "Leafes", "description" : "A very long neck" },
{ "name": "Lion", "food" : "Meat", "description" : "Featured in Lion King" }
]
},
{
"insects" : [
{ "name": "Ladybug", "food" : "Leafes", "description" : "Red and black" },
{ "name": "Spider", "food" : "Flies", "description" : "From the friendly neighbourhood" }
]
}
];
const wildAnimals = animals.find((item) => item.wildAnimals);
The code above basically checks which item in your array has a property called wildAnimals and returns that item. You can read more about this method Here.
Hope that helped!
I'm gonna suppose you are forced to use this format of storing data, but I feel like I have to let you know that this isn't the best way to store info like this (you will see that it is hard to work with it). Instead of having an array of objects, you could have an object of arrays like this:
let animals = {
"housePets": [{ "name": "Cat", "food": "Fish", "description": "Long tail, sharp claws" }, { "name": "Dog", "food": "Biscuits", "description": "Humans best friend" }],
"wildAnimals": [{ "name": "Giraffe", "food": "Leafes", "description": "A very long neck" }, { "name": "Lion", "food": "Meat", "description": "Featured in Lion King" }]
}
With this approach, getting all house animals would be as easy as animals.housePets.
Back to your issue tho. If you want to get all house animals from this, you will have to filter the array. To filter arrays, you have to give it a condition that the element has to pass to be stored. Here you can see that only the object with the house animals has a housePets property, so we can take advantage of that:
let house_animals = animals.filter(obj => obj.housePets)[0].housePets; // [{ "name": "Cat", "food": "Fish", "description": "Long tail, sharp claws" }, { "name": "Dog", "food": "Biscuits", "description": "Humans best friend" }]
What it does is that it takes all the objects that have the "housePets" property, takes the first one (I suppose there will always be only one) and reads the property, giving you the array of animals.
To find animals that are only in the housePets section and not in others, you can do this:
let house_animals = animals.filter(obj => obj.housePets)[0].housePets;
let wild_animals = animals.filter(obj => obj.wildAnimals)[0].wildAnimals;
let insects = animals.filter(obj => obj.insects)[0].insects;
let only_house = house_animals.filter(animal => !wild_animals.includes(animal) && !insects.includes(animal); // This checks if the animal is in the wild_animals or insects array. If it isn't, it keeps it.
You can also check this question out
Hope this helped :)
You can follow this code as a starting point. The complete example with updated data is below.
There are two key functions:
function _get(array, label): Take the array and get the names of the animals under the label category.
function _filterAndGet(mainList, filterList): Take the main list of animals, and filter out any animals that are in filter list. Then, pick a random animal from that filtered list.
Code
const animals = [
{
housePets : [{name: 'Cat', food : 'Fish', description: 'Long tail, sharp claws'}, {name: 'Dog', food : 'Biscuits', description : 'Humans best friend'}]
},
{
wildAnimals : [{name: 'Giraffe', food : 'Leafes', description : 'A very long neck'}, {name: 'Lion', food : 'Meat', description : 'Featured in Lion King'}, {name: 'Cat', food : 'Fish', description: 'Long tail, sharp claws'}, {name: 'Ladybug', food : 'Leafes', description : 'Red and black'}]
},
{
insects : [{name: 'Ladybug', food : 'Leafes', description : 'Red and black'}, {name: 'Spider', food : 'Flies', description : 'From the friendly neighbourhood'}]
}]
const wildAnimals = _get(animals, 'wildAnimals');
console.log(`Wild animals: ${JSON.stringify(wildAnimals)}`);
const housePetsAndInsects = _get(animals, 'housePets').concat(_get(animals, 'insects'));
console.log(`House Pets and Insects: ${housePetsAndInsects}`);
console.log(`Random wild animal not in housePets and insects: ${_filterAndGet(wildAnimals, housePetsAndInsects)}`);
function _filterAndGet(mainList, filterList) {
const filterSet = new Set(filterList);
const filteredMainList = mainList.filter(e => !filterSet.has(e));
const index = Math.floor(Math.random() * filteredMainList.length);
return filteredMainList[index];
}
function _get(array, label) {
const res = [];
for (const elem of array) {
for (const objKey of Object.keys(elem)) {
if (objKey === label) {
for (const item of elem[objKey]) {
res.push(item.name);
}
return res;
}
}
}
return res;
}
Example output:
Wild animals: ["Giraffe","Lion","Cat","Ladybug"]
House Pets and Insects: Cat,Dog,Ladybug,Spider
Random wild animal not in housePets and insects: Lion
You can try with this simple way by using Array.find() along with Array.some() methods.
Working Demo :
let animals = [{
"housePets": [
{ "name": "Cat", "food" : "Fish", "description": "Long tail, sharp claws" },
{ "name": "Dog", "food" : "Biscuits", "description" : "Humans best friend" }]
}, {
"wildAnimals": [
{ "name": "Giraffe", "food" : "Leafes", "description" : "A very long neck" },
{ "name": "Lion", "food" : "Meat", "description" : "Featured in Lion King" }]
}, {
"insects": [
{ "name": "Ladybug", "food" : "Leafes", "description" : "Red and black" },
{ "name": "Spider", "food" : "Flies", "description" : "From the friendly neighbourhood" }]
}];
let animalsArr2 = ['housePets'];
const res = animals.find((obj) => animalsArr2.some((elem) => Object.keys(obj).includes(elem)));
console.log(res);

how to get particular Keys Values from the exiting JSON Object in javacsript? [duplicate]

This question already has answers here:
How to get a subset of a javascript object's properties
(36 answers)
Closed 3 years ago.
I have one JSON Object and I want to create subset of JSON with particular keys values.
JSON Object
{
"Checksum": "OK",
"ID": "012B4567",
"DOB: "12-12-1991"
"Data": "Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>",
"issue: "11-April-2015",
"DocID": "PASSPORT",
"Number: "123456789",
"Document": "PASSPORT",
"Photo": "Qk06AAAAAAAAA",
"ExpiredFlag": false,
"ExpiryDate": "01 Apr 12",
"Forename": "IMA Phoney",
"Image2": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"ImageSource1": 0,
"Image3": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"Image1": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I want subset from above like below:
{
"ID": "012B4567",
"Number: "123456789",
"Document": "PASSPORT",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I have tried below code. It is working fine, But I am not able to understand. I need simplest way:
var data={
"CDRValidation": "CDR Validation test passed",
"AirBaudRate": "424",
"ChipID": "012B4567",
"BACStatus": "TS_SUCCESS",
"SACStatus": "TS_NOT_PERFORMED",
"Data": "Test Line 1 >>>>>\nTest Line 2 >>>>>\nTest Line 3 >>>>>",
"DocType": "PASSPORT",
"DocNumber": "123456789",
"DocID": "PASSPORT",
"Surname": "Person",
"Forename": "IMA Phoney",
"SecondName": "J",
"Nationality" : "Imaging Automation Demo State",
"Sex": "Male",
"DOB": "12 May 70",
"ExpiryDate": "01 Apr 12",
"IssueState": "Passport Agency Billerica",
"ExpiredFlag": false,
"ImageSource": 0,
"OptionalData1": "123456789123456",
"OptionalData2": "",
"DateOfIssue":"11 April 02",
"PlaceOfBirth":"Illinois, U.S.A"
}
console.log("----------------->",data);
var Fields = ({
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data, {
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
})
console.log("--------subset--------->",Fields);
There are multiple ways you can handle this case. Object destructuring as you have done in your example is one simple way. You can also use an array to store the required keys and write code as below
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
const obj = {};
for (let i = 0, length = keys.length; i < length; i += 1) {
obj[keys[i]] = parentObj[keys[i]];
}
return obj;
}
Or you can also use the above code with some functional programming
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
return keys.reduce((acc, key) => ({
...acc,
[key]: parentObj[key];
}), {});
}
A simple to achieve what you are asking using ES5 is to create a list of all the properties you want to keep, and using Array#reduce add each property to a new object.
// Saves vertical space for example
var original = JSON.parse(`{"Checksum":"OK","ID":"012B4567","DOB":"12-12-1991","Data":"Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>","issue":"11-April-2015","DocID":"PASSPORT","Number":"123456789","Document":"PASSPORT","Photo":"Qk06AAAAAAAAA","ExpiredFlag":false,"ExpiryDate":"01 Apr 12","Forename":"IMA Phoney","Image2":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","ImageSource1":0,"Image3":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","Image1":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","IssueState":"USA","Nationality":"USA","PlaceOfBirth":"U.S.A","SecondName":"J","Sex":"Male","Surname":"XYZ"}`);
var propertiesToUse = ["ID", "Number", "Document", "IssueState", "Nationality", "PlaceOfBirth", "SecondName", "Sex", "Surname"];
var result = propertiesToUse.reduce(function(result, key) {
return result[key] = original[key], result;
}, {});
console.log(result);
What you have done is a simple way, but if you are confused with it, you can divide it into two lines and explain it.
This line actually destrucutes your object and assign the value for the mentioned keys in the object to the corresponding variables.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data
Now, each of this variable has data individually, but we want it in an object. Therefore, we use the second part, i.e. creating an object with the following variable acting as keys.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
}
When combined you get the desired result in a single statement.

Is there a way to de-dupe a javascript array and combine values of the data?

I'm using an ajax request to grab some XML data which I then need to push into a chart in fusioncharts.
The XML data is formatted as [time taken], [work done], [which team done for], [who did it] (see below).
I'm iterating over the XML and then building the array using the code below:
//Time Recorded
if (columnidchecker == 7781) {
timearray.push($j(this).find('displayData').text());
temp1 = $j(this).find('displayData').text();
}
//Type of Activity
if (columnidchecker == 7782) {
activityarray.push($j(this).find('displayData').text());
temp2 = $j(this).find('displayData').text();
}
//Team Done For
if (columnidchecker == 7783) {
subjectarray.push($j(this).find('displayData').text());
temp3 = $j(this).find('displayData').text();
}
//Name
if (columnidchecker == 7777) {
internalclientarray.push($j(this).find('displayData').text());
temp4 = $j(this).find('userDisplayName').text();
}
});
//PUSH INTO A NEW ARRAY WHICH CAN THEN BE SORTED AND DE-DUPED WITH TIME COMBINED AGAINST ACTIVITY / TEAM.
objectarray.push([temp1, temp2, temp3, temp4]);
This builds an array of entries from the XML which basically outputs to something which looks like this:
0: (4) ["1.50", "Ad-hoc queries or calls", "Team 1", "James"]
1: (4) ["2.50", "Ad-hoc queries or calls", "Team 1", "James"]
2: (4) ["1.00", "Advice", "Team 2", "James"]
3: (4) ["3.50", "Meeting (External 3rd Party)", "Team 1", "James"]
4: (4) ["1.20", "Administration", Team 2", "James"]
5: (4) ["5.50", "Advice", "Team 1", "John"]
I'm trying to build a chart in fusioncharts which needs the format as shown below (ignore foot stuffs - it's taken straight from the fusioncharts help pages!).
{
"chart": {
"theme": "fusion",
"caption": "Revenue split by product category",
"subCaption": "For current year",
"xAxisname": "Quarter",
"yAxisName": "Revenues (In USD)",
"showSum": "1",
"numberPrefix": "$"
},
"categories": [
{
"category": [
{
"label": "Q1"
},
{
"label": "Q2"
},
{
"label": "Q3"
},
{
"label": "Q4"
}
]
}
],
"dataset": [
{
"seriesname": "Food Products",
"data": [
{
"value": "11000"
},
{
"value": "15000"
},
{
"value": "13500"
},
{
"value": "15000"
}
]
},
{
"seriesname": "Non-Food Products",
"data": [
{
"value": "11400"
},
{
"value": "14800"
},
{
"value": "8300"
},
{
"value": "11800"
}
]
}
]
}
The problem i'm having is that I cannot work out how to take the array of data with times, activity, team, name and push them into categories.
I think the first step is to create a new array of names which can be pushed into the "Category" data field in fusioncharts.
I then need a way in which to take the times being recorded against each activity and for each team and make sure it's assigned to the right person within the stacked bar chart and combine the amount of time spent. (i.e. "James" spent a total of 4 hours doing "Ad Hoc Queries and Calls" for Team 1 but this is split across two time entries so I need a way in which to combine them into one.)
Any help on this would be massively appreciated.
I can de-dupe the names to create a new array by using the following code:
namesarray.push(temp4);
uniq = [...new Set(namesarray)];
but after that it starts getting pretty complicated.
Maybe this can help you along the way. It's probably not exactly in the form you want it, but it demonstrates how you could break the problem down into smaller parts.
Pseudo-code:
get the unique names.
get the unique "task" names (for lack of a
better word)
for each unique person name:
3.1. get the data rows for that person
3.2 for each of all unique tasks names:
find the person data rows matching the task name
sum the duration of those data rows
const testData = [
[
"1.50",
"Ad-hoc queries or calls",
"Team 1",
"James"
],
[
"2.50",
"Ad-hoc queries or calls",
"Team 1",
"James"
],
[
"1.00",
"Advice",
"Team 2",
"James"
],
[
"3.50",
"Meeting (External 3rd Party)",
"Team 1",
"James"
],
[
"1.20",
"Administration",
"Team 2",
"James"
],
[
"5.50",
"Advice",
"Team 1",
"John"
]
];
const columnIndexByName = {
TASK_DURATION: 0,
TASK_NAME: 1,
FOR_WHICH_TEAM: 2,
PERSON_DOING_TASK: 3
};
const sum = (acc, next) => acc + next;
const uniqueNames = [...new Set(testData.map(row => row[columnIndexByName.PERSON_DOING_TASK])) ];
const uniqueTaskNames = [...new Set(testData.map(row => row[columnIndexByName.TASK_NAME])) ];
let result = {};
uniqueNames.forEach(personName => {
const personDataRows = testData.filter(row => row[columnIndexByName.PERSON_DOING_TASK] === personName);
let taskDurationsByTaskName = {};
uniqueTaskNames.forEach(taskName => {
const taskRows = personDataRows.filter(row => row[columnIndexByName.TASK_NAME] === taskName);
const taskDurations = taskRows.map(row => Number.parseFloat( row[columnIndexByName.TASK_DURATION] ));
const taskTotalDuration = taskDurations.reduce(sum, 0);
taskDurationsByTaskName[taskName] = taskTotalDuration;
})
result[personName] = taskDurationsByTaskName;
})
const renderData = data => document.querySelector("#output").innerHTML = JSON.stringify(data, null, 2);
renderData(result);
<pre id="output"></pre>

JSON data filtering using javaScript [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 4 years ago.
Improve this question
I have assigned a task to group data in angular js using underscore js.
My JSON :
data = [
{
"Building*": "Building A",
"Wing*": "Wing C",
"Floor*": "Floor 3",
"Room Name*": "Room 3",
"Room Type*": "AC",
"Location*": "Location 1",
"Device ID*": 27,
"Category*": "Soap Hygene",
"Dispenser Name*": "Dispenser 34",
"Type*": "Manual",
"Cartridge Type*": "Type 1",
"Date of installation": "2016-04-11T06:06:22 -06:-30",
"Contact Last Name": "Maynard",
"Email Address": "thomas.boscher#gmail.com",
"Mobile Number with country code": "+1 (949) 590-3465",
"Description": "Description of device",
"Model": 37
},
{
"Building*": "Building B",
"Wing*": "Wing B",
"Floor*": "Floor 3",
"Room Name*": "Room 1",
"Room Type*": "AC",
"Location*": "Location 3",
"Device ID*": 26,
"Category*": "Soap Hygene",
"Dispenser Name*": "Dispenser 33",
"Type*": "Manual",
"Cartridge Type*": "Type 2",
"Date of installation": "2015-07-24T12:42:24 -06:-30",
"Contact Last Name": "Holland",
"Email Address": "thomas.boscher#gmail.com",
"Mobile Number with country code": "+1 (947) 491-2353",
"Description": "Description of device",
"Model": 32
}
]
I need data in below format, where it has each building details containing the wing and floor data
updateData = [{
building: 'Building A' ,
buildingData:[ {
wing: "Wing A",
wingData: [{
floor:'Floor 2',
floorData:[{
room:'Room 3',
roomData:[]
}]
}]
}]
}];
I tried :
js fiddle
But it fails. Need help. Thanks in advance.
From my understanding you want to groupBy in the following nested order:
Building ->> Wing ->> Floor ->> Room
You can try calling groupBy recursively (or looping through, up to you) by passing an array of the order of nested attribute you want to groupBy. Try this snippet below:
const nestedOrder = ['Building*', 'Wing*', 'Floor*', 'Room Name*']
function groupFilter (rawData, attrList) {
if (attrList.length == 0) return rawData
var currentAttr = _(attrList).first()
return _(rawData)
.chain()
.groupBy(currentAttr)
.map((list, attrName) => Object({
[currentAttr]: attrName,
[`${currentAttr}Data`]: groupFilter(list, _(attrList).rest())
}))
.value()
}
console.log(groupFilter(data, nestedOrder))
The raw data will then be compacted to the deepest nested attribute, in this case 'Room Name*', you can then write your custom filter to output what you want RoomData to hold.
Not sure if its the right way to do it, but if runtime isnt a big issue for you then I think you can make it work fine.
Hopefully this helps/works out for you.

Combining nested objects [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 6 years ago.
Improve this question
I have an object like this:
"data" :[{"question": "FirtName", "answer": "Daniel"},
{"question": "LastNane", "answer": "Daniel2"},
{"question": "Age", "answer": "80"}]
I want to change it to this format using java script
"data":
["FirtName" : "Daniel", "LastNane" : "Daniel2", "Age" : "80"]
Please, assist me!
I propose a solution for a input as an array of objects and an output as an object
var data = [{question: "FirtName", answer: "Daniel"},
{question: "LastNane", answer: "Daniel2"},
{question: "Age", answer: 80}
];
var result = {};
data.forEach(x => {
result[x.question] = x.answer;
});
console.log(result);
Keep attention to your object, thats what it should look about.
var object={
"data" :[
{
"question": "FirtName",
"answer": "Daniel"
},{
"question": "LastNane",
"answer": "Daniel2"
},{
"question": "Age",
"answer": "80"
}
]
};
var newObject={};
object.data.forEach(function(question){
newObject[question.question]=question.answer;
});
// {"FirtName" : "Daniel", "LastNane" : "Daniel2", "Age" : "80"}
console.log(newObject);
This code will get you the output you require
var object = {
"data": [{
"question": "FirtName",
"answer": "Daniel"
}, {
"question": "LastNane",
"answer": "Daniel2"
}, {
"question": "Age",
"answer": "80"
}]
};
var result = '"data":' + JSON.stringify(object.data.reduce(function (result, item) {
return result[item.question] = item.answer, result;
}, {})).replace('{', '[').replace('}', ']');
console.log(result);
// "data":["FirtName":"Daniel","LastNane":"Daniel2","Age":"80"]
You can use Array.prototype.reduce to convert to the object you desire - see demo below:
var array = [{"question": "FirtName","answer": "Daniel"},{"question": "LastNane","answer": "Daniel2"}, {"question": "Age","answer": "80"}];
var result = array.reduce(function(p, c) {
p[c.question] = c.answer;
return p;
}, {});
console.log(result);

Categories

Resources