I would like to know how to convert the input json array to a json object in the expected format using Javascript
Here is my input array
[
{
"Id": 1,
"Name": "One"
},
{
"Id": 2,
"Name": "Two"
},
{
"Id": 3,
"Name": "Three"
}
]
Expected json object output
{ "1" : "One",
"2" :"Two",
"3" :"Three"
}
You can use array reduce and pass an empty object in the accumulator. Then inside the reduce callback update the accumulator array by adding key and value
let obj = [{
"Id": 1,
"Name": "One"
}, {
"Id": 2,
"Name": "Two"
}, {
"Id": 3,
"Name": "Three"
}]
let newObj = obj.reduce(function(acc, curr) {
acc[curr.Id] = curr.Name;
return acc;
}, {})
console.log(newObj)
let arr = [{
"Id": 1,
"Name": "One"
},
{
"Id": 2,
"Name": "Two"
},
{
"Id": 3,
"Name": "Three"
}
]
let json1 = {}
for (const s of arr) {
json1[s.Id] = s.Name
}
console.log(json1)
You only need a simple for loop to iterate trough the array and then assign new properties to the resulting object, like so:
let array = [{ "Id": 1, "Name": "One"}, {"Id": 2, "Name": "Two"}, {"Id": 3, "Name": "Three"}];
let obj = {};
for (let i = 0; i < array.length; i++) {
const elem = array[i];
obj[elem.Id] = elem.Name;
}
console.log(obj);
Iterate over the array of objects, use Object.values() to get the values for each object and then create new obects using the first value as the key.
var arr = [ { "Id": 1, "Name": "One" }, { "Id": 2, "Name": "Two" }, { "Id": 3, "Name": "Three" } ];
var jsonObj = {};
arr.forEach(function(item){
var values = Object.values(item);
jsonObj[values[0]] = values[1];
})
console.log(jsonObj); // gives {"1": "One","2": "Two","3": "Three"}
Related
I have an array of objects:
arr1 = [
{
"id": 1,
"color": "blue",
"label": "School",
},
{
"id": 2,
"color": "red",
"label": "Work",
}
]
and a simple array:
arr2 = [ 2, 5 ]
I want to write a method that returns true if one of the object ids from arr1 can be found in arr2. So I could use it with
v-if
later.
What's your suggestion?
let arr1 = [
{
"id": 1,
"color": "blue",
"label": "School",
},
{
"id": 2,
"color": "red",
"label": "Work",
}
]
let arr2 = [ 2, 5 ]
let arr1_id = arr1.map(function (obj) {
return obj.id;
});
function check(array1, array2) {
let intersection = array1.filter(element => array2.includes(element));
if (intersection.length > 0) {
return true
}
else {return false}
}
bool = check(arr1_id,arr2)
console.log(bool)
I need inner join with two array in javascript like this:
array1 =
[
{
"id": 1,
"name": "Tufan"
},
{
"id": 2,
"name": "Batuhan"
},
{
"id": 3,
"name": "Hasan"
}
]
array2 =
[
{
"name": "yyy",
"externalid": "1",
"value": "Asd"
},
{
"name": "aaaa"
"externalid": "2",
"value": "ttt"
}
]
expectedArray =
[
{
"id": 1,
"name": "Tufan",
"externalid": "1",
"value": "Asd"
},
{
"id": 2,
"name": "Batuhan",
"externalid": "2",
"value": "ttt"
}
]
rules:
on: array2.externalid = array1.id
select: array1.id, array1.name, array2.externalid, array2.value
My approach:
array1.filter(e => array2.some(f => f.externalid == e.id));
// I need help for continue
How can I make this?
Doesn't matter information: I use ES5 and pure javascript
You can do it like this:
const res = array2.map((item) => {
const related = array1.find((el) => el.id == item.externalid);
return { ...item, ...related };
});
Using a map to loop over the array2 and a find to get the array1 relative.
{
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
This is list of arrays with keys and values as array, I want to return all the keys based on a particular value;
For Eg:
I want to return the parent keys which are [arr1,arr2], reason being both the arrays contain a value Unique, So I want to return the parent key of both the values, which is arr1 and arr2 respectively.
Note: The list can have n numbers of arrays.
Any help would be appreciated. Thanks in advance.
The simplest way to go about this is:
Loop through the keys in your object
Check if the array contains any objects with the name "Unique"
If so, add the objects key to an array
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
// Create our array that will contain the keys
const keys = []
// Loop through each key in the object
for (const prop in obj) {
// Use .some to see if any of the objects in this array have the selected name
const containsUnique = obj[prop].some(o => o.name === 'Unique')
if (containsUnique) {
// Add the current key to the array
keys.push(prop)
}
}
// Use the array of keys which contain an object named "Unique"
console.log(keys)
This is a more generic approach:
const getKeysByValue = (data, value) => {
const dataKeys = Object.keys(data);
const valueKey = Object.keys(value);
return dataKeys.filter(currKey => {
for(let element of data[currKey])
if(element[valueKey] === value[valueKey])
return true;
});
}
const data = {
"arr1":[
{
"name":"something1",
"shape": "Trapezium",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"shape": "Octagon",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"shape": "Square",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"shape": "Triangle",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"shape": "Circle",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"shape": "Triangle",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
}
],
"arr3":
[
{
"name":"Not-Unique",
"shape": "Circle",
"id":"8hcf14ee58ea25g343e9a2f208df215c"
}
]
}
console.log(getKeysByValue(data, {"name": "something2"})); // ["arr1"]
console.log(getKeysByValue(data, {"name": "Unique"})); // ["arr1", "arr2"]
console.log(getKeysByValue(data, {"shape": "Circle"})); // ["arr1", "arr3"]
console.log(getKeysByValue(data, {"shape": "Square"})); // ["arr1"]
The function receives two parameters, data and value. value is expected to be in the format of the value you are looking to filter with. In your example you wanted it to be "Unique" and in each object in the array it was presented like "name": "Unique" so we will send it as an object, {"name": "Unique"}.
In this way you can have different value to filter with. In the example above I added a shape key and value to each element, we can filter by this value too as shown in the example above.
you can do like this :
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
arr=[]
//loop over dict with pair keys and value
for (const [key, value] of Object.entries(obj)) {
//get the list of name from dict and check it if it contains Unique string
value.map(e=>e.name).includes("Unique") ? arr.push(key) : false
}
console.log(arr)
You can use array some method
const data = {
"arr1": [{
"name": "something1",
"id": "233111f4-9126-490d-a78b-1724009fa484"
},
{
"name": "something2",
"id": "50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name": "something4",
"id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name": "something5",
"id": "ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2": [{
"name": "Unique",
"id": "43cf14ee58ea4d8da43e9a2f208d215c"
}]
}
var obj = [],
keys;
for (keys in data) {
data[keys].some(a => "Unique" === a.name) && obj.push(keys);
}
console.log(obj);
An alternative way that i could think of is using Regexp
var obj = {
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
let str = JSON.stringify(obj);
let match = str.matchAll(/\"([\w\d]+)\":\[(?:{[\s\S]+},)*{\"name\":\"Unique\"/g);
let parent = [];
for(let m of match){
parent.push(m[1]);
}
Array One:
array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}]
Array Two:
array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}]
Resulting Array:
resultingArray = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}],
"a_id" : {"id": 5, "name": "bcd"}
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}],
"a_id" : {"id": 4, "name": "bef"}
}]
I am looking to add the array2 objects into array1 based on id's of array2. I have tried using map function on both the arrays to compare and add the object but I didn't succeed. Can you please suggest me how to do it?
Thank you
Add the array2 objects into array1 based on ids of array2.
let array1 =
[
{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}
];
let array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}
];
let resultingArray=[];
array1.forEach(function(element) {
element['a_id'] = [];
element['attr'].forEach(function(attr) {
element['a_id'].push(array2.find(function(item) {
return item.id == attr.value;
}));
});
resultingArray.push(element)
});
console.log(resultingArray);
I presume you intend to extract the object whose ID is equal to the value field the in the each object in array1.
var array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}];
var array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}];
var resultingArray = [];
for(var i = 0; i < array1.length; i++) {
resultingArray[i] = array1[i];
for(var j = 0; j < array2.length; j++) {
if(resultingArray[i].attr[0].attr_code.value === array2[j].id) {
resultingArray[i].push("a_id": array2[j]);
}
}
}
You just need to lop through array1, and for each object in array1, you need to find corresponding objects in array2 which match the criterion.
You can use array map and array index to do:
var array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}];
var array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}];
var result = array1.map(current=>{
//find index of attr in array2
let index = array2.findIndex(c=>{
if (c['id']===(Number(current['attr'][0]['value'])))
return c;
});
current["a_id"] = array2[index];
return current;
});
console.log(result);
Please check if the following code suites your requirement. You may need to make some changes.
function mergeArrays3 (arr1, arr2) {
return arr1.map((value, index) => {
let object = null;
let result = {...value};
for (let element of arr2) {
if (element.id == parseInt(value.attr[0].value)) {
object = element;
break;
}
}
if (object != null) {
let attr = value.attr[0];
if (attr.hasOwnProperty("attr")) {
result[value.attr[0].attr] = object;
} else if (attr.hasOwnProperty("attr_code")) {
result[value.attr[0].attr_code] = object;
}
}
return result;
});
}
I loop over first array and find an element in second array matching id of value.attr[0].value. If found then i added this object in the first array at key of value.attr[0].attr or value.attr[0].attr_code.
I have tried using map function on both the arrays to compare and add
the object but I didn't succeed
Below is the functional programming approach using map():
/* GIVEN */
const array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{
"attr_code": "a_id",
"value": "5"
}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{
"attr": "a_id",
"value": "4"
}]
}
]
const array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}]
/* From array2, make an object keyed by the 'id' field. We'll use this as a key-value lookup table */
const lookupTable = array2.reduce((accum, item) => {
accum[item.id.toString()] = item
return accum
}, {})
console.log('***LOOKUP TABLE***\n', lookupTable) // result is an object we use to lookup
/* From array1, we append data from the lookup table */
const final = array1.map(item => {
item.a_id = lookupTable[item.attr[0].value]
return item
})
console.log("***RESULT***\n", final)
Hope this helps.
Cheers,
I have the array:
var tabs = [
{"id": 1, "Name": "Top", "Paris": 1, "London": 1, "Rome": 1},
{"id": 2, "Name": "Best", "Paris": 1, "London": 0, "Rome": 0},
{"id": 3, "Name": "Cheap", "Paris": 0, "London": 1, "Rome": 0}
];
How can I write a function that receives as argument one of the towns (London or Paris or Rome) different each time and returns the elements of the array which the argument is 1? For example, I want to take all the elements where London=1.
var tabs= [
{ "id": 1, "Name": "Top","Paris":1,"London":1, "Rome":1},
{ "id": 2, "Name": "Best","Paris":1,"London":0,"Rome":0},
{ "id": 3, "Name": "Cheap","Paris":0,"London":1,"Rome":0}
];
var getElementsWith=function(array,name){
var myElements=[];
array.forEach(function(tab){
if(tab[name]===1)
myElements.push(tab);
});
return myElements;
};
console.log(getElementsWith(tabs,"Paris"));
You can use Array.filter:
function filterList(cityName) {
return tabs.filter(function(o) {
return o[cityName] === 1;
});
}
You could use a generic function, which takes the array, key and value, you are looking for. Then use Array#filter for the sub set.
function filter(array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
}
var tabs = [{ "id": 1, "Name": "Top","Paris":1,"London":1, "Rome":1 },{ "id": 2, "Name": "Best","Paris":1,"London":0,"Rome":0 },{ "id": 3, "Name": "Cheap","Paris":0,"London":1,"Rome":0 }],
result = filter(tabs, 'London', 1);
console.log(result);