How to create a json object from two arrays in JavaScript - javascript

I have the following arrays
['a','b','c','d','e','f']
[1762, 770, 93, 474, 323, 351]
I would like to convert them into a list of json objects so that I end up with an object that looks a bit like this
{
"SomeObject": [
{
"name": "a",
"value": 1762
},
{
"name": "b",
"value": 770
},
{
"name": "c",
"value": 93
},
{
"name": "d",
"value": 474
},
{
"name": "e",
"value": 323
},
{
"name": "f",
"value": 351
}
]
}
How can I concert these arrays to the above object in JavaScript.
Thank you in advance

const keys = ['a','b','c','d','e','f'];
const values = [1762, 770, 93, 474, 323, 351];
const result = keys.map((key, i) => ({ name: key, value: values[i] }));
console.log(result);

Related

Search inside child Array of objects with multiple value

Currently i have below Array of Objects
const dataClass = [
{
"id": 101,
"class": [
{
"type": "A",
"value": "A-class"
},
{
"type": "B",
"value": "B-class"
},
{
"type": "C",
"value": "C-class"
}
],
"rank": 1
},
{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
},
{
"id": 103,
"class": [
{
"type": "G",
"value": "G-class"
},
{
"type": "H",
"value": "H-class"
},
{
"type": "I",
"value": "I-class"
}
],
"rank": 3
}
];
i need to get dataClass object using all value inside the class object, let say i want to get the second object, so i have to search/input "type": "D", "type": "E", and "type": "F".
return array object/object i expect:
[{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
}]
I don't find any solution so far, Thanks for any help.
I added one more object with types D, E, F at rank 4
If you want to return all objects that match your filtration, check result1
and if you just wanna return the first object that matches, check result2
const dataClass = [
{
"id": 101,
"class": [
{
"type": "A",
"value": "A-class"
},
{
"type": "B",
"value": "B-class"
},
{
"type": "C",
"value": "C-class"
}
],
"rank": 1
},
{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
},
{
"id": 103,
"class": [
{
"type": "G",
"value": "G-class"
},
{
"type": "H",
"value": "H-class"
},
{
"type": "I",
"value": "I-class"
}
],
"rank": 3
},
{
"id": 104,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 4
}
];
const expectedValues = ['D', 'E', 'F'];
//use this if you wanna return all objects that match expectedValues
const result1 = dataClass.filter(el => el.class.every(obj => expectedValues.includes(obj.type)));
console.log('all matched Objects => ', result1);
//use this if you wanna return the first object that match expectedValues
const result2 = dataClass.find(el => el.class.every(obj => expectedValues.includes(obj.type)));
console.log('first matched object => ',result2);
Hope this will help,
const dataClass = [
{
"id": 101,
"class": [
{
"type": "A",
"value": "A-class"
},
{
"type": "B",
"value": "B-class"
},
{
"type": "C",
"value": "C-class"
}
],
"rank": 1
},
{
"id": 102,
"class": [
{
"type": "D",
"value": "D-class"
},
{
"type": "E",
"value": "E-class"
},
{
"type": "F",
"value": "F-class"
}
],
"rank": 2
},
{
"id": 103,
"class": [
{
"type": "G",
"value": "G-class"
},
{
"type": "H",
"value": "H-class"
},
{
"type": "I",
"value": "I-class"
}
],
"rank": 3
}
];
const resultArr = [];
for (const ch_arr of dataClass){
for (const class_arr of ch_arr["class"]){
if(["D","E","F"].includes(class_arr["type"])){
resultArr.push(ch_arr);
break;
}
};
};
// resultArr is the expected array
You need find the object inside of class Array so i think using find method is the more readable way to solved it
function findClassByType(value: string) {
return [dataClass.find((obj) => obj.class.find(({ type }) => type.toLocaleLowerCase() === value.toLocaleLowerCase()))];
}
console.log(findClassByType('a'))
I added the toLocaleLowerCase to avoid case sensitive.

JSON convert with Javascript [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 a json file like as below
[{
"id": 2,
"name": "Ali",
"records":[{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
},{
"id": 3,
"name": "Mete",
"records":[{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]
I want to convert to like this
[{
"id": 2,
"name": "Ali",
record: {
"type": "L",
"total": 123
}
},{
"id": 2,
"name": "Ali",
record: {
"type": "P",
"total": 102
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "O",
"total": 100
}
},{
"id": 3,
"name": "Mete",
record: {
"type": "T",
"total": 88
}
}]
how can i do it using javascript?
Here is what you could do. However, this doesn't work in IE as is as Object.assign that is being used, isn't yet supported in IE. However, it could be replaced with any javascript object clone methods.
You could check : What is the most efficient way to deep clone an object in JavaScript?
var input = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}];
var output = [];
input.forEach((obj) => {
var records = obj.records;
delete obj.records;
records.forEach((record) => {
// Doesnt have any support in IE.
var newRecord = Object.assign({}, obj);
newRecord.record = record;
output.push(newRecord);
});
});
console.log(output);
If you are fine to use jQuery, here is what you could do.
var input = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}];
var output = [];
input.forEach((obj) => {
var records = obj.records;
delete obj.records;
records.forEach((record) => {
var newRecord = jQuery.extend({}, obj);
newRecord.record = record;
output.push(newRecord);
});
});
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a functional (but probably not very efficient) way of doing it:
function transform(data) {
// Merge the sub arrays together
return [].concat.apply([], (data.map(person => {
// Return an array of copied objects for each person
return person.records.map(record => {
// For each record, copy the person information
return {
id: person.id,
name: person.name,
record: record
};
});
})));
}
console.log(transform([{
"id": 2,
"name": "Ali",
"records":[{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
},{
"id": 3,
"name": "Mete",
"records":[{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]));
There's a few ways but Array.prototype.map seems to fit the bill. This blurb should get you started:
// We'll assume your original array is called myArray
var newArray = myArray.map ( function ( d ) {
return {
id : (d.id || 'theIDYouWant'),
name : (d.name || 'theNameYouWant' ),
record : { type : d.type, total : d.total }
}
} );
var jsonStr = JSON.stringify ( newArray );
console.log ( jsonStr ); // should write out your JSON as expected.
This will do it and save what you want in new_json
try running the code snippet below
json = [{
"id": 2,
"name": "Ali",
"records": [{
"type": "L",
"total": 123
}, {
"type": "P",
"total": 102
}]
}, {
"id": 3,
"name": "Mete",
"records": [{
"type": "O",
"total": 100
}, {
"type": "T",
"total": 88
}]
}]
new_json = [];
for (var i = 0; i < json.length; i++) {
for (j = 0; j < json[i]['records'].length; j++) {
new_json.push({
id: json[i]['id'],
name: json[i]['name'],
record: json[i]['records'][j]
})
}
}
console.log(new_json);

ES6: Find an object in an array by one of its properties

I'm trying to figure out how to do this in ES6...
I have this array of objects..
const originalData=[
{"investor": "Sue", "value": 5, "investment": "stocks"},
{"investor": "Rob", "value": 15, "investment": "options"},
{"investor": "Sue", "value": 25, "investment": "savings"},
{"investor": "Rob", "value": 15, "investment": "savings"},
{"investor": "Sue", "value": 2, "investment": "stocks"},
{"investor": "Liz", "value": 85, "investment": "options"},
{"investor": "Liz", "value": 16, "investment": "options"}
];
..and this new array of objects where I want to add each person's total value of their investment types (stocks, options, savings)..
const newData = [
{"investor":"Sue", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Rob", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Liz", "stocks": 0, "options": 0, "savings": 0}
];
I loop through originalData and save each property of the "current object" in a let..
for (let obj of originalData) {
let currinvestor = obj.investor;
let currinvestment = obj.investment;
let currvalue = obj.value;
..but here I want to find the obect in newData that has the property = currinvestor (for the "investor" key)
...then add that investment type's (currinvestment) value (currvalue)
}
newData.find(x => x.investor === investor)
And the whole code:
const originalData = [
{ "investor": "Sue", "value": 5, "investment": "stocks" },
{ "investor": "Rob", "value": 15, "investment": "options" },
{ "investor": "Sue", "value": 25, "investment": "savings" },
{ "investor": "Rob", "value": 15, "investment": "savings" },
{ "investor": "Sue", "value": 2, "investment": "stocks" },
{ "investor": "Liz", "value": 85, "investment": "options" },
{ "investor": "Liz", "value": 16, "investment": "options" },
];
const newData = [
{ "investor": "Sue", "stocks": 0, "options": 0, "savings": 0 },
{ "investor": "Rob", "stocks": 0, "options": 0, "savings": 0 },
{ "investor": "Liz", "stocks": 0, "options": 0, "savings": 0 },
];
for (let {investor, value, investment} of originalData) {
newData.find(x => x.investor === investor)[investment] += value;
}
console.log(newData);
.as-console-wrapper.as-console-wrapper { max-height: 100vh }
I would use some derivative of this:
var arrayFindObjectByProp = (arr, prop, val) => {
return arr.find( obj => obj[prop] == val );
};

manipulating JSON array data

I have a JSON array from DB, and I want it to manipulate. Currently it has discreet 8 elements, I want the array to manipulate it to get 2 elements, rest elements will be nested. My current JSON has this structure:
{
"itemId": 1,
"desc": [{
"type": "A",
"size": "xx",
"count": 12,
"price": 122
},
{
"type": "A",
"size": "xl",
"count": 18,
"price": 180
},
{
"type": "B",
"size": "xx",
"count": 12,
"price": 122
},
{
"type": "B",
"size": "xl",
"count": 12,
"price": 122
}]
}
I want the data to be manipulated to come like this:
{
"type": "A",
"desc":{
"size": "xx",
"count": 12,
"price": 122
},
{
"size": "xl",
"count": 12,
"price": 122
},
},
{
"type": "B",
"desc":{
"size": "xx",
"count": 12,
"price": 122
},
{
"size": "xl",
"count": 12,
"price": 122
},
}
I am using for each loop, but this is creating individual elements, i want just two elements in the resulting array.
Any solution will be appreciated.
You could try something like this:
var new_data = {
A: {type: 'A', desc: []},
B: {type: 'B', desc: []}
};
$.each(data.desc, function( index, value ) {
new_data[value.type].desc.push(value);
});
https://jsfiddle.net/5cnaxn04/
If you don't know the types you will get, you can build the object dynamically:
var new_data = {};
$.each(data.desc, function( index, value ) {
if(typeof new_data[value.type] === "undefined") {
new_data[value.type] = {type: value.type, desc: [value]}
} else {
new_data[value.type].desc.push(value);
}
});
https://jsfiddle.net/5cnaxn04/1/
You have some syntax errors in your code, as you are using {} for both Arrays and Objects, so I'd guess from the context. You need a few loops to make the data look exactly to what you want.
See JSFiddle.

Set the value of a variable to another variable for same keys

I have two variables array1 and array2 as following and I want to put the values of array2 into array1 for the properties present in array1 and rest of the properties should remain the same with default values.
One solution I have is to iterate through the array length and set values for found properties and but my array is too long to perform iteration (the array supplied in this question is just a raw value).
I need some better way other than iteration.
var array1=[
{
"name": "a",
"value": 0,
"level": [
{
"name": "a1",
"value": 0
},
{
"name": "a2",
"value": 0
}
]
},
{
"name": "b",
"value": 0,
"level": [
{
"name": "b1",
"value": 0
},
{
"name": "b2",
"value": 0
}
]
},
{
"name": "c",
"value": 0,
"level": [
{
"name": "c1",
"value": 0
},
{
"name": "c2",
"value": 0
}
]
}
]
var array2=[
{
"name": "a",
"value": 1,
"level": [
{
"name": "a1",
"value": 1
},
{
"name": "a2",
"value": 0
}
]
},
{
"name": "b",
"value": 1,
"level": [
{
"name": "b1",
"value": 0
},
{
"name": "b2",
"value": 1
}
]
}
]
and the required output is
var final_array=[
{
"name": "a",
"value": 1,
"level": [
{
"name": "a1",
"value": 1
},
{
"name": "a2",
"value": 0
}
]
},
{
"name": "b",
"value": 1,
"level": [
{
"name": "b1",
"value": 0
},
{
"name": "b2",
"value": 1
}
]
},
{
"name": "c",
"value": 0,
"level": [
{
"name": "c1",
"value": 0
},
{
"name": "c2",
"value": 0
}
]
}
]
A recursive solution with two iterators, one for arrays iterateA and one for objects iterateO. This proposal uses the thisArg for reference to json2.
Basically both callbacks iterates over the items or keys and checks if this is set and if the actual item is present in this. if not, the function returns.
The rest is straight forward, if an object is found, then it iterates over the keys and the object, if an array is found, the it it iterates over the array.
Only in the case of k === 'value' the value of this[k] is to o[k] assigned.
var json1 = [{ "name": "a", "value": 0, "level": [{ "name": "a1", "value": 0 }, { "name": "a2", "value": 0 }] }, { "name": "b", "value": 0, "level": [{ "name": "b1", "value": 0 }, { "name": "b2", "value": 0 }] }, { "name": "c", "value": 0, "level": [{ "name": "c1", "value": 0 }, { "name": "c2", "value": 0 }] }],
json2 = [{ "name": "a", "value": 1, "level": [{ "name": "a1", "value": 1 }, { "name": "a2", "value": 0 }] }, { "name": "b", "value": 1, "level": [{ "name": "b1", "value": 0 }, { "name": "b2", "value": 1 }] }];
function iterateO(o) {
return function (k) {
if (!this || !(k in this)) {
return;
}
if (typeof o[k] === 'object') {
Object.keys(o[k]).forEach(iterateO(o[k]), this[k]);
return;
}
if (Array.isArray(o[k])) {
o[k].forEach(iterateA, this[k]);
return;
}
if (k === 'value') {
o[k] = this[k];
}
};
}
function iterateA(a, i, aa) {
if (!this || !(i in this)) {
return;
}
if (typeof a === 'object') {
Object.keys(a).forEach(iterateO(a), this[i]);
return;
}
if (Array.isArray(a)) {
a.forEach(iterateA, this[i]);
return;
}
}
json1.forEach(iterateA, json2);
document.write('<pre>' + JSON.stringify(json1, 0, 4) + '</pre>');

Categories