Here is the sample json data that I have:
a = [
{
"first_name": "Andrew",
"last_name": " ",
"job": "actor",
},
{
"first_name": "Andrew",
"last_name": "Petrov",
"job": "",
"contry": "Russia"
},
{
"first_name": "Andrew",
"last_name": "Petrov",
"contry": "Russia"
},
]
And I want to extract the single object from this array and make a new array from this object.
This is the sample output which I wants to get:
[
{
"first_name": "Andrew",
"last_name": "Petrov",
"job": "actor",
"contry": "Russia"
}
]
As simple as a[1]
[n] is the index of the array. Index starts at 0
If you mean to get an object in array in array, a[1][0]
I think this should get you to the result you want. Basically what I am doing is using the array.reduce method to iterate over all the objects in the input array and add the properties that are missing in the result object.
let a = [
{
"first_name": "Andrew",
"last_name": " ",
"job": "actor",
},
{
"first_name": "Andrew",
"last_name": "Petrov",
"job": "",
"contry": "Russia"
},
{
"first_name": "Andrew",
"last_name": "Petrov",
"contry": "Russia"
},
]
let result = a.reduce((prevValue, currentValue) => {for (let prop in currentValue) {
if (currentValue[prop].trim() && !prevValue[prop]) {
prevValue[prop] = currentValue[prop];
}
}
return prevValue;
}, {});
console.log(result);
In array you can get the n th item by providing the index number to it.
For example:
a = [10, 11, 12]
if you want's to get the 10 from this array you can do console.log(a[0]) which will log the 10 in your console. In here a[0] 0 is the index.
Same as in your condition: if you wants to get the object from your array you need to pass the index number of that particular object.
In your case, a[0] will return this output:
{
"first_name": "Andrew",
"last_name": " ",
"job": "actor",
}
Now the second case that you want is , you need to create a new array from this object.
There are number of ways to create an array, here is the simple one:
const myNewArray = [a[0]]
If you wrap your object with big brackets, it'll create a new array.
In your case, there are some fields which are missing in objects, to get that, there are number of ways that you can use like: reducer, map, forEach loop etc.
Here is the example with reducer:
let res = a.reduce((xs, cv) => {
for (let prop in cv) {
if (cv[prop].trim() && !xs[prop]) {
xs[prop] = cv[prop];
}
}
return xs;
}, {});
console.log("result is :", res)