json object from javascript nested array - javascript

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!

If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.

You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

Related

Array of arrays to array of Objects

const events = [
[{
createdAt: "2021-12-06T16:32:59.260Z"
location: "Off-Site"
name: "Viewing"
}],
[{
createdAt: "2021-12-06T16:32:59.260Z"
...
}],
..........
]
Hi I have question. From the above can i be able to convert the data to somethin like
const events = [
{
createdAt: "2021-12-06T16:32:59.260Z"
location: "Off-Site"
},
{
createdAt: "2021-12-06T16:32:59.260Z"
...
},
..........
]
if anyone knows please answer
Use Array.flat method
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified dept
const arr = [[1,2,3],[4,5]];
const res = arr.flat()
console.log(res)

JavaScript Get Indexes based from the Selected Array of Object Id

Today, I'm trying to get the list of javascript index based from the selected data id that I have.
I'm following this guide from https://buefy.org/documentation/table/#checkable where it needs something like this: checkedRows: [data[1], data[3]] to able to check the specific row in the table.
What I need to do is to check the table based from my web API response.
I have this sample response data.
response.data.checkedRows // value is [{id: 1234}, {id: 83412}]
and I have the sample data from the table.
const data = [{
id: 1234,
name: 'Jojo'
},{
id: 43221,
name: 'Jeff'
},{
id: 83412,
name: 'Kacey'
}]
So basically, I need to have something, dynamically, like this: checkedRows: [data[0], data[2]] because it matches the data from the response.data.checkedRows
So far, I tried using forEach
let selectedIndex = [];
response.data.checkedRows.forEach((d) => {
this.data.forEach((e) => {
if (d.id=== e.id) {
// need the result to be dynamic depending on the response.data.checkedRows
this.checkedRows = [data[0], data[2]]
}
});
});
I'm stuck here because I'm not sure how can I get the index that matches the selected checkedRows from response.
Any help?
Map the response checkedRows, and in the callback, .find the matching object in the array:
const checkedRows = [{id: 1234}, {id: 83412}];
const data = [{
id: 1234,
name: 'Jojo'
},{
id: 43221,
name: 'Jeff'
},{
id: 83412,
name: 'Kacey'
}];
const objs = checkedRows.map(({ id }) => (
data.find(obj => obj.id === id)
));
console.log(objs);
If there are a lot of elements, you can use a Set of the IDs to find instead to decrease the computational complexity:
const checkedRows = [{id: 1234}, {id: 83412}];
const data = [{
id: 1234,
name: 'Jojo'
},{
id: 43221,
name: 'Jeff'
},{
id: 83412,
name: 'Kacey'
}];
const ids = new Set(checkedRows.map(({ id }) => id));
const objs = data.filter(obj => ids.has(obj.id));
console.log(objs);

Javascript filter parent array based on child containing value

I am trying to filter the parent array products based on the selected value which should be contained as the child. For example in my case I was trying to get all the product objects as an array which contained the string "iphone". It is not working for me and I can't seem to locate my error. Please may someone help.
What I have tried:
const selected = 'iphone'
const products = [
{
id: "4irnflpd0",
productItem: [ "iphone", "ipad", "kindle"],
},
{
id: "glrscb1m3s9k",
productItem: ["airpods","iphone",],
},
{
id: "uumkugk3jxof",
productItem: ["macbook","cable"]
},
]
var filtered = products.map(o=>{
o = Object.assign({},o); //Clone the object. So any changes will not affect the original array.
o.productItem.map(p=>{ //Use map to loop thru the products
p = p.filter(v=>v === selected); //Filter the products which include selected
});
return o;
})
Expected array output:
const products = [
{
id: "4irnflpd0",
productItem: [ "iphone", "ipad", "kindle"],
},
{
id: "glrscb1m3s9k",
productItem: ["airpods","iphone",],
},
]
Just a simple filter() method should work for us in this case. T further simplify, we can also use object restructuring, so instead of writing product.productItem.includes(selected), we'll only need to write productItem.includes(selected).
All we have to do is filter the source array by which items include the selected value:
const selected = 'iphone';
const products = [
{ id: "4irnflpd0", productItem: ["iphone", "ipad", "kindle"] },
{ id: "glrscb1m3s9k", productItem: ["airpods", "iphone", ] },
{ id: "uumkugk3jxof", productItem: ["macbook", "cable"] },
];
const filtered = products.filter(({productItem}) => productItem.includes(selected));
console.log(filtered);
If you'd prefer not to use Object destructuring, just swap that filter line for this more traditional one:
products.filter(p => p.productItem.includes(selected))
If you're not sure that every single item in your array will have the productItem key, then you should use optional chaining to prevent an error being thrown. This is as simple as adding ? before after property name. Here it is all put together:
products.filter(p => p.productItem?.includes(selected))
First of all no need to make a copy since with map function you allocated the result to new variable without changing the new array
So you need to do this
const filtered = products.map(p=>{
return p.productItem.includes(selected)
})
You can use the filter() methods on products array and find if the selected item is available in the productItems
const selected = 'iphone'
const products = [
{ id: "4irnflpd0", productItem: [ "iphone", "ipad", "kindle"] },
{ id: "glrscb1m3s9k", productItem: ["airpods","iPhone",] },
{id: "uumkugk3jxof", productItem: ["macbook","cable"] }
]
var filtered = products.filter(product =>
product.productItem?.includes(selected));
console.log(filtered);

Filtering array of objects against another array of objects?

customerProducts: [
{
name: "foo",
id: 123
},
{
name: "test",
id: 44
}
]
otherProducts: [
{
name: "other",
id: 44
},
{
name: "test",
id: 21
}
]
I want to iterate through customerProducts, which is an array of objects. I want to filter the customerProducts that have an ID that another array of objects, otherProducts, has. So for examople, I'd want the returned result in this case to be:
{
name: "test",
id: 44
}
since otherProducts has an id of 44.
I was thinking of mapping through otherProducts and just returning an array of IDs, then running a forEach on that but that seems like a long way of doing it.
Create an indexed Set of the values to filter by (id from otherProducts) then filter customerProducts by that Set
const customerProducts = [{name: "foo",id: 123},{name: "test",id: 44}]
const otherProducts = [{name: "other",id: 44},{name: "test",id: 21}]
const otherProductIds = new Set(otherProducts.map(({ id }) => id))
const filteredCustomerProducts = customerProducts.filter(({ id }) =>
otherProductIds.has(id))
console.info(filteredCustomerProducts)
This can be done by using array methods filter and some.
customerProducts.filter((x)=> otherProducts.some(y=> y.id === x.id));
Explanation:
filter method will call each and every element in the otherProducts array and check if the id of customerProduct is present in otherProducts for at least one element.
declare customerProducts , otherProducts as JS array variable and use JS Array filter find functions
let customerProducts = [
{
name: "foo",
id: 123
},
{
name: "test",
id: 44
}
]
let otherProducts = [
{
name: "other",
id: 44
},
{
name: "test",
id: 21
}
];
let filtered = customerProducts.filter( el => otherProducts.find( e => e.id == el.id) )
console.log(filtered);

How to get JSON keys and add extra fields?

I'm trying to get the key of these json objects in order to create a new object with extra filed to create table headers in a React app. JSON data:
let example = [
{
id: 1,
city: 'New York',
},
{
id: 2,
city: 'Paris',
},
]
The function:
getKeys() {
return example.map((key) => {
return {
cityName: key, // gets the whole array
capital: false,
};
});
}
I tries Object.keys( example);, it returns integers; 0, 1.
How can I get the keys in this case? Thanks.
You are trying to map the keys for an array since example is an array. If the data are consistent throughout the array get the first element example[0] and do Object.keys().
So Object.keys(example[0])
There's no need to get the keys if you just want to add a property to the items in the array. I think there's a misunderstanding about .map, which gives you a single item/object in the array, not the keys.
Something like this perhaps?
let example = [{
id: 1,
city: 'New York',
}, {
id: 2,
city: 'Paris',
}];
const modifiedArray = function(arr) {
return arr.map(item => {
return {
id: item.id,
cityName: item.city,
capital: false,
};
})
}
const newArray = modifiedArray (example);
console.log(newArray )

Categories

Resources