I want to create new array based on keyword.
if my search key word is
const myarray = [
{
"align-center": [
"align",
"center"
]
},
{
"align-justify": [
"align",
"justified"
]
},
{
"align-left": [
"align",
"left",
"arrow"
]
},
{
"align-right": [
"align",
"right",
"arrow"
]
}
]
let results = myarray.filter(function (name) { return *****
});
First use map()
to get the key of each object in the array. Then use filter()
to return the ones that match the search string.
let searchKey = 'left';
function search(array, searchKey) {
return array.map(obj => Object.keys(obj)[0]).filter(key => key.includes(searchKey));
}
console.log(search(myarray, 'align-center'));
console.log(search(myarray, 'align'));
console.log(search(myarray, 'right'));
<script>
const myarray = [{
"align-center": [
"align",
"center"
]
},
{
"align-justify": [
"align",
"justified"
]
},
{
"align-left": [
"align",
"left",
"arrow"
]
},
{
"align-right": [
"align",
"right",
"arrow"
]
}
];
</script>