29
loading...
This website collects cookies to deliver better user experience
const someObject = {
"type" : "Objects",
"data": [
{
"id" : "1",
"name" : "Object 1",
"type" : "Object",
"attributes" : {
"color" : "red",
"size" : "big",
"arr": [1,2,3,4,5]
},
},
{
"id" : "2",
"name" : "Object 2",
"type" : "Object",
"attributes" : {}
},
]
}
console.log(
someObject.data[0].attributes.color
)
// red
console.log(
someObject.data[1].attributes.color
)
// undefined
console.log(
someObject.data[0].attributes.arr[1]
)
// 2
console.log(
someObject.data[1].attributes.arr[1]
)
// TypeError: Cannot read property '1' of
// undefined
someObject.data[0].attributes.arr[0] = 200;
console.log(someObject.data[0].attributes.arr);
// [ 200, 2, 3, 4, 5 ]
someObject.data[1].attributes.arr[0] = 300;
// TypeError: Cannot set property '0' of
// undefined
console.log(
someObject?.data[1]?.attributes?.color
)
// undefined
console.log(
someObject?.data?.[1]?.attributes?.arr?.[0]
)
// undefined
get(object, path, [defaultValue])
npm install lodash
const _ = require('lodash');
console.log(
_.get(someObject,
'data[1].attributes.color',
'not found')
)
// not found
console.log(
_.get(someObject,
'data[1].attributes.arr[0]')
)
// undefined
npm install rambda
console.log(
R.pathOr(
["data", 1, "attributes", "color"],
someObject,
"not found")
);
// not found
console.log(
R.path(
["data", 1, "attributes", "arr", 0],
someObject
)
);
// undefined
set(object, path, value)
const _ = require("lodash");
_.set(
someObject
,"data[1].attributes.arr[1]"
, 200
);
console.log(
_.get(
someObject,
'data[1]'
)
)
/*
{
id: '2',
name: 'Object 2',
type: 'Object',
attributes: {
arr: [
<1 empty item>,
200
]
}
}
*/
const R = require("ramda");
const newObj =
R.assocPath(
['data','1','attributes','arr',1]
,200
,someObject
)
console.log(
R.path(['data','1'],newObj)
)
/*
{
id: '2',
name: 'Object 2',
type: 'Object',
attributes: {
arr: [
<1 empty item>,
200
]
}
}
*/