Home > Blockchain >  Javascript some for nested array
Javascript some for nested array

Time:09-20

this is my json data

userpayment":[{"_id":"63297d5d1ae7697c5130fc8a","user_id":"632525106df51baf8b582803","coursepack":[{"third":"63291808acb84985480536b4"}]}]

here "63291808acb84985480536b4" how to some from this json

my code below

userpayment.some(
    items => items.coursepack.some(
        its => its.third === "63291808acb84985480536b4"
    )
) ? true : false

CodePudding user response:

this is your JSON data:

let userpayment = '[{"_id":"63297d5d1ae7697c5130fc8a","user_id":"632525106df51baf8b582803","coursepack":[{"third":"63291808acb84985480536b4"}]}]'

we'll make an experment:

console.log(typeof userpayment ); // string

as you see js read userpayment as a string, not array containing an object, so you first need to convert it from string to JS Object using JSON.parse()

let JSOBJ = JSON.parse(userpayment);
console.log(typeof JSOBJ); // object

now we have an array contains object:

console.log(JSOBJ);

enter image description here

NOW you can some that array or do anything like seeing length... deal with it as a normal array

JSOBJ.some(
    items => items.coursepack.some(
        its => its.third === "63291808acb84985480536b4"
    )
) ? console.log(true) : console.log(false)

CodePudding user response:

Given the first line is actually JSON - you need to parse it, then perform the .some on the correct path in the object

const json = '{"users":{ "userpayment":[{"_id":"63297d5d1ae7697c5130fc8a","user_id":"632525106df51baf8b582803","coursepack":[{"third":"63291808acb84985480536b4"}]}]}}';
const data = JSON.parse(json);

const result = data.users.userpayment.some(items => items.coursepack.some(its =>its.third === "63291808acb84985480536b4"))

console.log(result);

or with minimal changes to your code (no changes)

const json = '{"users":{ "userpayment":[{"_id":"63297d5d1ae7697c5130fc8a","user_id":"632525106df51baf8b582803","coursepack":[{"third":"63291808acb84985480536b4"}]}]}}';
const {users: {userpayment}} = JSON.parse(json);

const result = userpayment.some(items => items.coursepack.some(its =>its.third === "63291808acb84985480536b4"))

console.log(result);

CodePudding user response:

Check This one,

let y = [{
        "userpayment" : {
            "_id":"63297d5d1ae7697c5130fc8a",
            "user_id":"632525106df51baf8b582803",
            "coursepack":[{ 
                "third":"63291808acb84985480536b4"
            }]
        }
        
    }]


let yo = y.map( item => {
    
    const { userpayment } = item
    
    return userpayment.coursepack.some((itemCourse) => {
        return itemCourse.third == "63291808acb84985480536b4"
    })

})

console.log(yo)

  • Related